I'm new to R and am struggling to to figure this out. I have a data fame with a column of character vectors that contain comma separated lists of things. I want to keep that column but add a column for each item with a value of 0 (not in the list) or 1 (in the list).
Here's what's I'm trying:
library("tidyverse")
colors <- c("red;blue", "red;green")
df <- data.frame(colors, stringsAsFactors = FALSE)
df %>%
mutate(green = case_when("green" %in% strsplit(colors,";")[[1]] ~ 1,
TRUE ~ 0))
The result I get is:
colors green
1 red;blue 0
2 red;green 0
I expected the value for "green" in the second row to be 1.
To try to debug this I tried this:
> strsplit("red;green", ";")
[[1]]
[1] "red" "green"
> "green" %in% strsplit("red;green",";")[[1]]
[1] TRUE
# and the negative case
> "green" %in% strsplit("red;blue",";")[[1]]
[1] FALSE
What am I missing?