r - 根据字符串中的模式创建虚拟变量(使用 mutate)

标签 r tidyverse recode

我试图弄清楚如何根据字符串中的模式创建虚拟变量。重点是最终以一种简单的方法使我的 ggplot 的某些方面(颜色、线型等)对于具有共同点的样本(例如同一基因的不同类型的突变 - 每个样本名称)相同包含基因的名称,加上一些其他字符)。

作为 iris 数据集的示例,假设我想添加一列(我的虚拟变量),该列对于名称包含字母“v”的物种有一个值,对于不包含字母“v”的物种有另一个值。 (在真实的数据集中,我有更多可能的类别。)

我一直在尝试使用 mutaterecodestr_detectif_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/

相关文章:

r - Dplyr加入: NA match to any

r - 如何在 R tidyverse 中转换列类型

c++ - H.264 快速重新编码

R:从矩阵中提取相对于行/列位置的值

r - 将数据框添加为列表元素(用于循环)

R 如何在给定起点和终点的 Tibble 中生成序列

r - 当它实际上是一个因素时,是否有更快的方法来重新编码字符数据?

R:如何一次重新编码多个变量

r - FSelector information.gain 测量什么?

r - 合并两个 data.frames 并用 df2 的值替换 df1 某些列的值