I have the following data frame with character values separated by spaces. I would like to create new columns for each unique value, thus turning the values into binary variables.
df <- data.frame("letter" = c("a", "b c a", "b a", "c b"))
This is the output I want to get:
df$a <- grepl("a", df$letter)
df$b <- grepl("b", df$letter)
df$c <- grepl("c", df$letter)
This is what I have tried:
list <- c("a", "b", "c")
replace_func <- function(x, df) {
df[[x]] <- grepl("[x]", df$letter)
return(df[[x]])
}
lapply(1:list, function(x) replace_func(x, df))
and this:
lapply(list, function(x) df[[x]] <- grepl("[x]", df$letter))