0

Is it possible to split a string and then use the split to create new variables?

For example, data is "Red", "Blue", "Red Blue", "Red Blue Green"

I would like to capture those who selected "Red", "Blue", "Green" in a matching "True/False" variable AND create a (selected more than one) "Multicolor" variable.

I have used

str_split(data$race, "\n", n=3) which shows me the splits but I need help with creating the variables from the splits.

  • 8
    Please make a [great reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) and give an example of your desired output. – Martin Gal Jul 21 '21 at 21:50

1 Answers1

0

Do you have something like that in mind?

library(tidyverse)
df <- data.frame(id=(1:5),
                 string=c("Red", "Blue", "Red Blue", "Red Blue Green", "Red Green"))
df <- df %>% mutate(words = sapply(strsplit(string, " "), length)) %>% 
  mutate(Multicolor = words > 1) %>% 
  mutate(Red = words == 1 & string == "Red") %>% 
  mutate(Blue = words == 1 & string == "Blue") %>% 
  mutate(Green = words == 1 & string == "Green") %>% 
  select(-words)
Bloxx
  • 1,495
  • 1
  • 9
  • 21