在dplyr中使用like运算符

在dplyr中使用like运算符,r,dplyr,R,Dplyr,我有一个篮球数据,有很多不同类型的投篮,我想减少不同名字的数量。例如,我有“后退跳投”和“上拉跳投” 我想添加一个新变量,其作用如下: df %>% mutate(NewVar== case when(Var1 like jumpshot then Jumpshot)) 因此,我所有不同的Jumpshot都被重命名为Jumpshot。要详细说明@r2evans的评论,您需要的是grepl()。此函数可以告诉您一个字符串是否存在于另一个字符串中。它将返回一个TRUE或FALSE。实际上,您

我有一个篮球数据,有很多不同类型的投篮,我想减少不同名字的数量。例如,我有“后退跳投”和“上拉跳投”

我想添加一个新变量,其作用如下:

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

因此,我所有不同的Jumpshot都被重命名为Jumpshot。

要详细说明@r2evans的评论,您需要的是
grepl()
。此函数可以告诉您一个字符串是否存在于另一个字符串中。它将返回一个TRUE或FALSE。实际上,您不需要突变或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


要详细说明@r2evans注释,您需要的是
grepl()
。此函数可以告诉您一个字符串是否存在于另一个字符串中。它将返回一个TRUE或FALSE。实际上,您不需要突变或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


别忘了str_detect from stringr

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

df <- data.frame(Var1,stringsAsFactors = FALSE) 

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


Var1别忘了从stringr检测stru\u

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

df <- data.frame(Var1,stringsAsFactors = FALSE) 

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


Var1当(grepl(“jumpshot”,Var1)~“jumpshot”,grepl(“block”,Var1)~“block”,TRUE~Var1)
我将尝试在这里找出如何执行该操作时,您是否可以使用dput()函数
df%>%case\u共享可复制的示例。这仍然是新的,应该是
df%>%变异(NewVar=case\u when(…)
)。你有
==case\u when
,这是不正确的。你能用dput()函数
df%>%case\u when(grepl(“jumpshot”,Var1)~“jumpshot”,grepl(“block”,Var1)~“block”,TRUE~Var1)
来分享一个可重复的例子吗?我会在这里试着弄清楚怎么做。这仍然是新的,应该是
df%>%变异(NewVar=case\u when(…)
)。您在
时有
==case\u,这是不正确的。