我试图弄清楚如何根据字符串中的模式创建虚拟变量。重点是最终以一种简单的方法使我的 ggplot 的某些方面(颜色、线型等)对于具有共同点的样本(例如同一基因的不同类型的突变 - 每个样本名称)相同包含基因的名称,加上一些其他字符)。
作为 iris 数据集的示例,假设我想添加一列(我的虚拟变量),该列对于名称包含字母“v”的物种有一个值,对于不包含字母“v”的物种有另一个值。 (在真实的数据集中,我有更多可能的类别。)
我一直在尝试使用 mutate
和 recode
、str_detect
或 if_else
,但不能'语法似乎不正确。例如,
mutate(iris,
anyV = ifelse(str_detect('Species', "v"), "withV", "noV"))
不会抛出任何错误,但它也不会检测到任何物种名称包含 v。我认为这与我无法弄清楚如何让 str_detect
工作有关:
iris %>%
select(Species) %>%
str_detect("setosa")
仅返回[1] FALSE
。
iris %>%
filter(str_detect('Species', "setosa"))
也不起作用。
(我还尝试过基于 7 Most Practically Useful Operations When Wrangling Text Data in R 中的示例的变异/重新编码解决方案,但也无法使其发挥作用。)
我做错了什么?我该如何解决它?
最佳答案
这有效:
library(stringr)
iris%>% mutate(
anyV = ifelse(str_detect(Species, "v"), "withV", "noV"))
Sepal.Length Sepal.Width Petal.Length Petal.Width Species anyV
1 5.1 3.5 1.4 0.2 setosa noV
2 4.9 3.0 1.4 0.2 setosa noV
3 4.7 3.2 1.3 0.2 setosa noV
4 4.6 3.1 1.5 0.2 setosa noV
5 5.0 3.6 1.4 0.2 setosa noV
...
52 6.4 3.2 4.5 1.5 versicolor withV
53 6.9 3.1 4.9 1.5 versicolor withV
54 5.5 2.3 4.0 1.3 versicolor withV
55 6.5 2.8 4.6 1.5 versicolor withV
56 5.7 2.8 4.5 1.3 versicolor withV
57 6.3 3.3 4.7 1.6 versicolor withV
58 4.9 2.4 3.3 1.0 versicolor withV
59 6.6 2.9 4.6 1.3 versicolor withV
嵌套 ifelse
语句的替代方法:
iris%>% mutate(newVar = case_when(
str_detect(.$Species, "se") ~ "group1",
str_detect(.$Species, "ve") ~ "group2",
str_detect(.$Species, "vi") ~ "group3",
TRUE ~ as.character(.$Species)))
关于r - 根据字符串中的模式创建虚拟变量(使用 mutate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43552028/