I have a large df file from a survey platform. the columns contains one question(as a title) with all potential answer. I'm trying to separate each of this answer column into a new set of columns (with the name of answer as the the name of the new column).
after that i would like each new column to indicate if the value appears in the original column(with "1") to process the data more easily
df<-data.frame("name"= c("John","mark","bell","elsa"),"what do you like to
eat"=c("apple","fries apple","peach","bread"))
original df
| name | What.do.you.like.to.eat |
|---|---|
| John | apple |
| Mark | fries apple |
| bell | peach |
| elsa | bread |
i'm using this code which works, but i'm sure there must be more efficient/easier way of doing it, as i have a over 50 column like this.
df<-df %>%
separate(what.do.you.like.to.eat, c("apple","fries","peach","bread",NA ), remove = F)
df[,3:6]<-""
{
df[,3] = with(df, ifelse(grepl("apple", df$what.do.you.like.to.eat,ignore.case = T),
paste('1', df[,3]),
paste("", df[,3])))
df[,4] = with(df, ifelse(grepl("fries", df$what.do.you.like.to.eat,ignore.case = T),
paste('1', df[,4]),
paste("", df[,4])))
df[,5] = with(df, ifelse(grepl("peach", df$what.do.you.like.to.eat,ignore.case = T),
paste('1', df[,5]),
paste("", df[,5])))
df[,6] = with(df, ifelse(grepl("bread", df$what.do.you.like.to.eat,ignore.case = T),
paste('1', df[,6]),
paste("", df[,6])))
}
desire output
| name | What.do.you.like.to.eat | apple | fries | peach | bread |
|---|---|---|---|---|---|
| John | apple | 1 | |||
| Mark | fries apple | 1 | 1 | ||
| bell | peach | 1 | |||
| elsa | bread | 1 |