lundi 19 août 2019

Getting the wrong association with ifelse function

I have a big data.frame and need to create a column with a categorical variable "Season" of Column "Month".

structure(list(year = c("2017", "2017", "2017", "2017", "2017", 
"2017", "2017", "2017", "2017", "2017", "2017", "2017", "2017", 
"2017", "2017", "2017", "2017", "2017", "2017", "2017", "2017", 
"2017", "2017", "2017", "2017", "2017", "2017", "2017", "2017", 
"2017", "2017", "2017", "2017", "2017", "2017", "2017", "2017", 
"2017", "2017", "2017", "2017", "2017", "2017", "2017", "2017", 
"2017", "2017", "2017", "2017", "2017"), month = c(1, 2, 2, 1, 
1, 3, 3, 3, 3, 4, 4, 4, 4, 4, 3, 1, 3, 3, 4, 5, 1, 2, 2, 2, 2, 
3, 1, 1, 2, 3, 4, 5, 6, 2, 5, 8, 1, 1, 4, 2, 3, 4, 2, 2, 2, 3, 
3, 4, 4, 1), day = c("29", "12", "12", "25", "25", "01", "01", 
"29", "29", "10", "10", "10", "10", "10", "14", "31", "02", "28", 
"25", "31", "21", "18", "12", "01", "01", "28", "07", "18", "16", 
"30", "26", "24", "22", "12", "16", "13", "10", "10", "11", "01", 
"28", "29", "04", "01", "01", "28", "28", "29", "29", "10")), row.names = c(NA, 
-50L), class = c("tbl_df", "tbl", "data.frame"))

I used the ifelse function like bellow:

a <- c(3,4,5)
b <- c(6,7,8)
c <- c(9,10,11)
d <- c(12,1,2)

df$season <- ifelse(df$month == a, "Spring",
               ifelse(df$month == b, "Summer",
                      ifelse(df$month == c, "Fall",
                             ifelse(df$month == d, "Winter",
                           ""))))


But I am getting the wrong association in the column Season. Many values that should have a season name is " ".

I also tried:

df[df$month == a, ][, "Season"] <- "Spring"
df[df$month == b, ][, "Season"] <- "Summer"
df[df$month == c, ][, "Season"] <- "Fall"
df[df$month == d, ][, "Season"] <- "Winter"

But did not work.

Could anyone help me please?

Aucun commentaire:

Enregistrer un commentaire