Let's pretend I have a data frame with species that display colors.
df<-data.frame(name=paste("spec",1:5),
ind=c("blue;green","red","green","red;green;blue",""))
And some (blue and red) of the colors actually mean something. I can just grepl() them and get a T/F-column
df$isredorblue<-grepl("blue|red",df$ind)
But now I want to know which of the meaningful colors were displayed in a column.
The desired result is:
> df
name ind isredorblue searchcolor
1 spec 1 blue;green TRUE blue
2 spec 2 red TRUE red
3 spec 3 green FALSE other
4 spec 4 red;green;blue TRUE red;blue
5 spec 5 FALSE other
I have tried gsub with a [^]+ but that doesn't really work because it matches all the letters so "r" or "e" or "d" not "red"...
> gsub("[^red]+","",df$ind)
[1] "eree" "red" "ree" "redreee" ""
And now I'm thinking of using strsplit... but can't seem to figure out my next step(s)
blabla<-strsplit(df$ind, split=";")
blabla<-blabla[-which(!blabla %in% c("red","blue"))]
> blabla
[[1]]
[1] "red"
Please keep in mind this is a reprex, my actual data frame is a lot larger and there are different indicators "colors" that matter for different things so I need to be able to produce these columns in as few steps as possible