I am trying to detect if specific keywords and phrases are present in a string, and if they are I want to post a specific number in a new column. My issue is that some strings have multiple keywords, but case_when only returns the first match. Is there way to fix this, or an alternative to case_when that I should be using?
ID<-c(1,2,3,4,5)
fruits<-c("banana apple orange", "apple orange", "orange", "orange apple", "nothing")
df<-data_frame(ID,fruits)
#I need to assign a random number to each fruit type
df %>%
mutate("Fruit Type"=case_when(
grepl("banana",fruits)~34,
grepl("apple",fruits)~45,
grepl("orange",fruits)~88,
))
ID fruits Fruit Type
1 banana apple orange 34
2 apple orange 45
3 orange 88
4 orange apple 45
5 nothing NA
I expected it to come out like this.
ID fruits fruit_type
1 banana apple orange 34
1 banana apple orange 45
1 banana apple orange 88
2 apple orange 45
2 apple orange 88
3 orange 88
4 orange apple 88
4 orange apple 45
5 nothing NA
Additionally, is there a way to convert this to long format in order to make it appear more like this?
ID fruits fruit_type fruit_type2 fruit_type3
1 banana apple orange 34 45 88
2 apple orange 45 88 NA
3 orange 88 NA NA
4 orange apple 88 45 NA
5 nothing NA NA NA