[英]Filtering rows with group by and matching different strings in multiple columns
[英]Searching matching rows in different columns
我正在寻找一个可以在列之间找到匹配项并输出的函数,如果找到匹配的行则输出"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))
提前致谢!
使用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
只需将%in%
与ifelse
一起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
,然后在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.