That's because ifelse
is vectorized whereas if
is not. You want something like:
month_map <- rep(c("Winter", "Spring", "Summer", "Fall"), each = 3)
month_map <- c(month_map[-1], month_map[1]) # tag December to be Winter
month.pos$SEA <- month_map[1 + (month.pos$MONTH - 1 + ifelse(month$X < 0, 6, 0)) %% 12]
The statement ifelse(month$X < 0, 6, 0)
will add 6 months if X
is negative (i.e. you are in the southern hemisphere), which corresponds to your taxonomy above. The %% 12
trick will roll things like 13 and 14 back to 1 and 2 because of adding the ifelse
.
Example
month.pos <- data.frame(MONTH = round(runif(100, 1, 12)))
month <- data.frame(X = runif(100, -1, 1))
head(cbind(month.pos, month), 10)
# MONTH X
# 1 8 -0.55105406
# 2 3 0.97186211
# 3 9 -0.99687710
# 4 6 -0.92899175
# 5 7 -0.61108006
# 6 10 0.66565870
# 7 4 0.77975565
# 8 10 -0.54498417
# 9 7 -0.04759831
# 10 10 -0.26378151
month.pos$SEA <- month_map[1 + (month.pos$MONTH - 1 + ifelse(month$X < 0, 6, 0)) %% 12]
head(month.pos, 10)
# MONTH SEA
# 1 8 Winter
# 2 3 Spring
# 3 9 Spring
# 4 6 Winter
# 5 7 Winter
# 6 10 Fall
# 7 4 Spring
# 8 10 Spring
# 9 7 Winter
# 10 10 Spring