查找不同列中的相交行并标记它们

时间:2018-03-23 17:47:38

标签: r dplyr

我正在寻找有关如何在数据框中正确标记相交行的解决方案。

这样

df = data.frame(id=c("good","bad","ugly","dirty","clean","frenzy"),di=c("good",2,"good","dirty",4,"ugly"))

> df
      id    di
1   good  good
2    bad     2
3   ugly  good
4  dirty dirty
5  clean     4
6 frenzy  ugly

我想创建列名match,如果有共同的相交行值,则将它们标记为intersected其他no.intersect

我试过

df%>%
  mutate(match=ifelse(isTRUE(intersect(id,di)),"intersected","no.intersect"))

并输出

      id    di        match
1   good  good no.intersect
2    bad     2 no.intersect
3   ugly  good no.intersect
4  dirty dirty no.intersect
5  clean     4 no.intersect
6 frenzy  ugly no.intersect

虽然第1行和第4行有一个交叉点。

2 个答案:

答案 0 :(得分:1)

library(dplyr)

# example dataframe
# (non factor variables)
df = data.frame(id=c("good","bad","ugly","dirty","clean","frenzy"),
                di=c("good",2,"good","dirty",4,"ugly"), 
                stringsAsFactors = F)

# check equaity of values at each row
df %>% mutate(match = ifelse(id == di, "intersected", "no.intersect"))

#       id    di        match
# 1   good  good  intersected
# 2    bad     2 no.intersect
# 3   ugly  good no.intersect
# 4  dirty dirty  intersected
# 5  clean     4 no.intersect
# 6 frenzy  ugly no.intersect    

此外,如果您想使用intersect,可以像这样使用它:

df %>%
  rowwise() %>%
  mutate(match = ifelse(length(intersect(id,di)) > 0, "intersected", "no.intersect")) %>%
  ungroup()

# # A tibble: 6 x 3
#   id     di    match       
#   <chr>  <chr> <chr>       
# 1 good   good  intersected 
# 2 bad    2     no.intersect
# 3 ugly   good  no.intersect
# 4 dirty  dirty intersected 
# 5 clean  4     no.intersect
# 6 frenzy ugly  no.intersect

因为intersect没有矢量化(所以你需要rowwise)并且它不会返回TRUE或FALSE(所以你不能使用isTRUE)。如果匹配则返回实际值,如果没有匹配则返回任何值。

答案 1 :(得分:0)

如果您正在尝试比较id和di之间的相等性,请尝试:

df %>% mutate(match = ifelse(id == di, "intersected", "no.intersect"))