1

I would like to create a new column in my data.frame: mad$season that is filled with conditional categories:

mad$season <- ifelse(mad$dayofyear <81, "winter", "")
mad$season <- ifelse((mad$dayofyear>=80) & (mad$dayofyear<=108), "spring", "")
mad$season <- ifelse(mad$dayofyear >108, "summer", "")

Similar to this example: R: Add multiple new columns based on multiple conditions

However, each line of code replaces the first - and NULL doesn't appear to work.

Any suggestions?

This question is different from Replacing numbers within a range with a factor because I wanted to add a new column, not replace the number with a factor.

Community
  • 1
  • 1

2 Answers2

0

We can use cut to do this without multiple ifelse statements. Just specify the breaks and the labels to create the 'season' column

mad$season <- with(mad, cut(dayofyear, breaks = c(-Inf, 80, 108, Inf),
         labels = c("winter", "spring", "summer")))
akrun
  • 874,273
  • 37
  • 540
  • 662
0

Just for the sake of you knowing what was wrong, in order to use multiple ifelse statements to do as you'd like, you have to nest them.

mad$season <- ifelse(mad$dayofyear <81, "winter", 
                     ifelse((mad$dayofyear>=80) & (mad$dayofyear<=108), "spring", 
                            ifelse(mad$dayofyear >108, "summer", "")))

This way, each time the ifelse if finds FALSE, it moves to the next available ifelse. Otherwise you are indeed rewriting the object.

As akrun has commented, cut is the much more clever way to do this.

Hope this helps.

Evan Friedland
  • 3,062
  • 1
  • 11
  • 25