是否可以拆分一个字符串,然后使用拆分来创建新的变量?
例如,数据是“红”、“蓝”、“红蓝”、“红蓝绿”。
我想捕捉那些在匹配的“真/假”变量中选择“红”、“蓝”、“绿”的人,并创建一个(选择多个) "Multicolor“变量。
我用过
str_split(data$race, "\n", n=3)
,它向我显示了拆分,但我需要帮助从拆分创建变量。
发布于 2021-07-22 06:19:25
你有这样的想法吗?
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)
https://stackoverflow.com/questions/68476803
复制相似问题