In R, I have a data frame, which has a column 'food' with 100+ different string values.
For instance:
id<-c("1", "2", "3", "4", "5", "6")
food <- c("X1_", "X2_", "X3_", "X4_", "X5_", "X100_")
df <- data.frame(id, food)
I would like to create a new column ‘food_final’ based on the strings in the column ‘food’. I started writing the code using nested ifelses and grepl, but given that there are 100+ different string values, I know having 100+ if elses is definitely not the cleanest way of doing this and in any case, there is a limit to how many one can have.
Example of what I have tried so far:
df$food_final<-ifelse(grepl("X1_", df$food, ignore.case=TRUE), "1",
ifelse(grepl("X2_", df$food, ignore.case=TRUE), "2",
ifelse(grepl("X3_", df$food, ignore.case=TRUE), "3",
ifelse(grepl("X4_", df$food, ignore.case=TRUE), "4",
ifelse(grepl("X5_", df$food, ignore.case=TRUE), "5",
ifelse(grepl("X100_", df$food, ignore.case=TRUE), "100", NA))))))
What is the best way of creating this new column 'food_final', instead of using so many nested ifelse statements?
Thank you in advance.