I am looking for a function that can find matches in between the columns and output if it finds a matching row outputs "has matches"
else "no matches"
for example
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
I want to check di
column has matches or not in id
column such that
> 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
This kind of approach what I am looking for
match_func <- function(x,y){
}
df%>%
do(match_func(.$id,.$di))
Thanks in advance!
Using base R
and without if/else
statement, you can compute match
column with:
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
Just use %in%
with ifelse
df %>%
mutate(match = ifelse(di %in% id, "has matches", "no matches"))
Or case_when
df %>%
mutate(match = case_when(di %in% id ~ "has matches",
TRUE ~ "no matches"))
This can be directly wrapped in a function. Assuming that we are passing unquoted names, then convert it to quosure with enquo
and then evaluate within the mutate
by !!
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.