我正在寻找能够在列和输出之间找到匹配项的函数,如果找到匹配的行输出"has matches"
则"no matches"
例如
df = data.frame(id=c("good","bad","ugly","dirty","clean","frenzy"),di=c(1,2,"good","dirty",4,"ugly"))
> df
id di
1 good 1
2 bad 2
3 ugly good
4 dirty dirty
5 clean 4
6 frenzy ugly
我想在di
列中检查id
列是否匹配,以便
> df
id di match
1 good 1 no matches
2 bad 2 no matches
3 ugly good has matches
4 dirty dirty has matches
5 clean 4 no matches
6 frenzy ugly has matches
我正在寻找的这种方法
match_func <- function(x,y){
}
df%>%
do(match_func(.$id,.$di))
提前致谢!
答案 0 :(得分:4)
使用base R
而不使用if/else
语句,您可以使用以下代码计算match
列。
df$match <- c("no matches", "has matches")[(df$di %in% df$id) + 1]
df
# id di match
#1 good 1 no matches
#2 bad 2 no matches
#3 ugly good has matches
#4 dirty dirty has matches
#5 clean 4 no matches
#6 frenzy ugly has matches
答案 1 :(得分:3)
只需将%in%
与ifelse
df %>%
mutate(match = ifelse(di %in% id, "has matches", "no matches"))
或case_when
df %>%
mutate(match = case_when(di %in% id ~ "has matches",
TRUE ~ "no matches"))
这可以直接包含在一个函数中。假设我们传递了不带引号的名称,然后使用enquo
将其转换为quosure,然后在mutate
内!!
进行评估
f1 <- function(dat, col1, col2) {
col1 = enquo(col1)
col2 = enquo(col2)
dat %>%
mutate(match = case_when(!! (col1) %in% !!(col2) ~ "has matches",
TRUE ~ "no matches"))
}
f1(df, di, id)
# id di match
#1 good 1 no matches
#2 bad 2 no matches
#3 ugly good has matches
#4 dirty dirty has matches
#5 clean 4 no matches
#6 frenzy ugly has matches