rif-statementsplitconditional-statements

R how to recreate new columns based on an if statement


I have a long column that contains the results of selected items separated by commas within the same cell. I want to create new columns based on conditions.

example

favorite_fruits <- c("apples,grapes,oranges," , "apples" , "grapes, oranges" , "oranges" ,"apples,grapes,oranges," , "apples" , "grapes,oranges" , "oranges")

I want to create new columns based on conditionals from this original column. For example, create a new column called orange that if a row in column favorite_fruits contains "oranges" then its = 1 if not then 0, same for apples, and grapes.

Thank you in advance.


Solution

  • data <- data.frame(favorite_fruits)
    
    fruit <- unique(trimws(unlist(strsplit(favorite_fruits, ","))))
    data[fruit] <- +sapply(fruit, grepl, x=favorite_fruits)
    

    Gives:

             favorite_fruits apples grapes oranges
    1 apples,grapes,oranges,      1      1       1
    2                 apples      1      0       0
    3        grapes, oranges      0      1       1
    4                oranges      0      0       1
    5 apples,grapes,oranges,      1      1       1
    6                 apples      1      0       0
    7         grapes,oranges      0      1       1
    8                oranges      0      0       1