I have a data frame with a column ("name") that contains names of fruits:
name
Apple
Apple
Mango
Banana
Banana
Orange
Mango
Orange
.... And so on. I have 9 fruits in my data
I want to create new variables following the naming rule "name_'data'". So, I want to add 9 more variables such that:
name name_Apple name_Mango name_Banana name_Orange
Apple 1 0 0 0
Apple 1 0 0 0
Mango 0 1 0 0
Banana 0 0 1 0
Banana 0 0 1 0
Orange 0 0 0 1
Mango 0 1 0 0
Orange 0 0 0 1
I want to use a for loop to do this since data will be added to the existing frame. I have tried this:
name_list <- c("Apple", "Mango", "Banana", "Orange)
for (i in name_list) {
df_main$name_[[i]] <- ifelse(df_main$name == [[i]], 1, 0)
}
I get the error "Error: unexpected '[['". I think I'm referencing character data wrong in the loop, but can't figure out how to do it correctly. Will mutate() work better here?