首页 > 解决方案 > 在 dplyr 中使用 like 运算符

问题描述

我有一个包含一堆不同类型投篮的篮球数据,我想减少不同名称的数量。例如,我有“后撤步跳投”和“引体向上跳投”。

我想添加一个执行以下操作的新变量:

df %>% mutate(NewVar== case when(Var1 like jumpshot then Jumpshot))

所以我所有不同的跳投都被重命名为跳投。

标签: rdplyr

解决方案


要详细说明@r2evans 评论,您要查找的是grepl(). 这个函数可以告诉你一个字符串是否存在于另一个字符串中。它将返回 TRUE 或 FALSE。您实际上并不需要 mutate 或 case when,并且可以使用 Base R 来做到这一点:

Var1 <-  c("Free Throw", "stepback jumpshot", "pull up jumpshot", "hail mary")

df <- data.frame(Var1) 

df$Var2 <- ifelse(grepl("jumpshot", Var1, fixed = TRUE), "Jumpshot", Var1)

df

#                Var1       Var2
# 1        Free Throw Free Throw
# 2 stepback jumpshot   Jumpshot
# 3  pull up jumpshot   Jumpshot
# 4         hail mary  hail mary

但是,如果您真的想使用dplyr函数,@r2evans 给出的 case 语句将起作用:


Var1 <-  c("Free Throw", "stepback jumpshot", "pull up jumpshot", "hail mary")

df <- data.frame(Var1) 

df2 <- df %>% 
  mutate(Var2 = case_when(grepl("jumpshot", Var1) ~ "Jumpshot", 
                          grepl("block", Var1) ~ "Block", 
                          TRUE ~ Var1))
df2

#                Var1       Var2
# 1        Free Throw Free Throw
# 2 stepback jumpshot   Jumpshot
# 3  pull up jumpshot   Jumpshot
# 4         hail mary  hail mary


推荐阅读