0

I am trying to add a new coloumn to my dataframe, based on a variable value. But everything comes out as "Period 1" instead of executing what is in my else if statements.

tar_year <- total_long_numeric$variable

total_long_numeric["Period"] <- if(tar_year == 1960 && tar_year <= 1969) {
  total_long_numeric$Period = "Period 1"
} else if (tar_year <= 1979) {
  total_long_numeric$Period = "Period 2"
} else if (tar_year <= 1989) {
  total_long_numeric$Period = "Period 3"
} else if (tar_year <= 1999) {
  total_long_numeric$Period = "Period 4"
} else if (tar_year <= 2009) {
  total_long_numeric$Period = "Period 5"
} else {
  total_long_numeric$Period = "Period 6"
} 
Ronak Shah
  • 355,584
  • 18
  • 123
  • 178
  • 1
    Use `ifelse` which is vectorised, `if` works only for single value. See this post https://stackoverflow.com/questions/12979456/categorize-numeric-variable-into-group-bins-breaks on how to use `cut` with `labels` which would be easier. – Ronak Shah Aug 20 '21 at 04:32

0 Answers0