Reputation: 21
I'm learning the 'for loop' command in R and I wanted to create a code that told you your zodiac sign.
m <- c("January", "February", "March", "April","May","June","July","August","September","October","November","December")
for(m in "January":"December") {
if (m == "March"|"April" )
next
}
print(paste("You are an Aries"))
When I run this I receive the errors 'Error in "January":"December" : NA/NaN argument' and '2: In "January":"December" : NAs introduced by coercion'. How do I remove those?
Upvotes: 0
Views: 534
Reputation:
There is a built-in vector with month names: month.name
.
To make a for
loop just type:
for(i in month.name) {...}
To check whether the month is March or April, use %in%
, e.g.:
if (i %in% c("March", "April") {...}
So your code could be:
for(i in month.name) {
if (i %in% c("March", "April")) {
print(paste(i, "- you are an Aries."))
} else {
print(paste(i, "- you are not in Aries."))
}
}
#> [1] "January - you are not in Aries."
#> [1] "February - you are not in Aries."
#> [1] "March - you are an Aries."
#> [1] "April - you are an Aries."
#> [1] "May - you are not in Aries."
#> [1] "June - you are not in Aries."
#> [1] "July - you are not in Aries."
#> [1] "August - you are not in Aries."
#> [1] "September - you are not in Aries."
#> [1] "October - you are not in Aries."
#> [1] "November - you are not in Aries."
#> [1] "December - you are not in Aries."
Created on 2020-07-09 by the reprex package (v0.3.0)
Upvotes: 1
Reputation: 269431
Any of these three snippets will print the names of each month except for March and April. month.name
is a vector that is built into R containing the names of the months.
for(m in month.name) {
if (m %in% c("March", "April")) next
print(m)
}
for(m in setdiff(month.name, c("March", "April"))) print(m)
print(setdiff(month.name, c("March", "April")))
Upvotes: 2