r - 在 dplyr 中使用 like 运算符
问题描述
我有一个包含一堆不同类型投篮的篮球数据,我想减少不同名称的数量。例如,我有“后撤步跳投”和“引体向上跳投”。
我想添加一个执行以下操作的新变量:
df %>% mutate(NewVar== case when(Var1 like jumpshot then Jumpshot))
所以我所有不同的跳投都被重命名为跳投。
解决方案
要详细说明@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
推荐阅读
- gnome-shell-extensions - 应用新样式时如何更新小部件
- pandas - 如何获取以下代码来抓取此网页中列出的所有菜单项?
- html - Bootstrap Carousel 幻灯片动画问题
- c++ - 为什么这个堆栈变量没有被覆盖,尽管它超出了范围?
- java - 我可以动态生成实现两个或多个接口的类吗?
- java - Java、Android、camerax 编程。错误:找不到符号。符号:类生成器
- c# - 无法构建干净的 VSIX 项目:尝试加载不存在的 Newtonsoft.Json?
- javascript - 如何在 $.ajax 调用中使用变量调用成功函数
- ios - 在 AVPlayerViewController 全屏视图上呈现 UIView
- ios - 如何为静态 TableView 单元格点击添加操作?