不管怎么说,是否可以使用dplyr中的recode函数和来自DescTools的%like%操作符以及一个“other”语句?即如下所示:
library(tidyverse)
library(DescTools)
dat <- data.frame(NAME = c("Bill", "Billy", "Wibill", "Chris"))
dat %>%
mutate(NAME_2 = recode(NAME, "%Bill%" = "Willhelm", "Other"))期望的产出是:
NAME NAME_2
Bill Willhelm
Billy Willhelm
Wibill Willhelm
Chris Other发布于 2020-06-02 18:08:20
这不是recode()的工作方式;recode()将特定的值与特定的替换相匹配。但是,使用mutate()和if_else()很容易实现所需的输出。
dat %>%
mutate(NAME_2 = if_else(NAME %like% "%[Bb]ill%", "Willhelm", "Other"))
NAME NAME_2
1 Bill Willhelm
2 Billy Willhelm
3 Wibill Willhelm
4 Chris Other(尽管您会注意到,我不得不考虑大写或小写的"Bill",如果您想要的输出不以这种方式区分大小写,%like%的任何用法都是如此。)
发布于 2020-06-02 19:10:24
grepl在base R中的另一个选项
dat$NAME_2 <- with(dat, ifelse(grepl("Bill", NAME, ignore.case = TRUE), "Willhelm", "Other"))https://stackoverflow.com/questions/62158088
复制相似问题