使用case_when进行变异并包含 [英] mutate with case_when and contains

查看:129
本文介绍了使用case_when进行变异并包含的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我觉得应该有一种有效的方法,使用 case_when 和<$ c使用 dplyr 来突变新列$ c>包含,但无法正常使用。

I feel like there should be an efficient way to mutate new columns with dplyr using case_when and contains, but cannot get it to work.

我知道在 mutate 中使用 case_when 是有点实验性(如文章),但

I understand using case_when within mutate is "somewhat experimental" (as in this post), but would be grateful for any suggestions.

不起作用:

library(tidyverse)

set.seed(1234)

x <- c("Black", "Blue", "Green", "Red")

df <- data.frame(a = 1:20, 
                 b = sample(x,20, replace=TRUE))

df <- df %>%
  mutate(group = case_when(.$b(contains("Bl")) ~ "Group1",
                 case_when(.$b(contains("re", ignore.case=TRUE)) ~ "Group2")
  )  


推荐答案

我们可以使用 grep

df %>%  
   mutate(group = case_when(grepl("Bl", b) ~ "Group1",
                            grepl("re", b, ignore.case = TRUE) ~"Group2"))
#    a     b  group
#1   1 Black Group1
#2   2 Green Group2
#3   3 Green Group2
#4   4 Green Group2
#5   5   Red Group2
#6   6 Green Group2
#7   7 Black Group1
#8   8 Black Group1
#9   9 Green Group2
#10 10 Green Group2
#11  1 Green Group2
#12  2 Green Group2
#13  3  Blue Group1
#14  4   Red Group2
#15  5  Blue Group1
#16  6   Red Group2
#17  7  Blue Group1
#18  8  Blue Group1
#19  9 Black Group1
#20 10 Black Group1

这篇关于使用case_when进行变异并包含的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆