jeudi 18 février 2016

Create a new column conditional to a list in R

I am trying to create a new column conditional to my column Decision_list (which is a list). I would like to assign the colour red whenever Upwind is in the string, and blue when Upwind is missing.

df_sub <- structure(list(Index = c(14L, 788L, 789L, 792L, 793L), Decision_list = list(
    "NoDetection", c("NoDetection", "Upwind", "Upwind"), c("NoDetection", 
    "Upwind"), c("NoDetection", "Upwind", "Upwind"), c("NoDetection", 
    "Upwind", "Upwind"))), .Names = c("Index", "Decision_list"
), row.names = c(NA, 5L), class = "data.frame")

I tried:

df_sub$NewColumn <-
        ifelse(df_sub$Decision_list %in% c("Upwind"), "Red",      
"Blue")

or something looking like:

gh <- df_sub$Decision_list
for( i in seq_along(gh)){   
    ff <- gh[[i]]
  gh[[i]] <- ifelse(unlist(ff) %in% c("Upwind"), "Red",       
"Blue")
}

Both options failed to create the column I want. For example with option 1, I get blue 5 times while I should get it only for the first row. Any help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire