R列表的交集

时间:2019-03-04 16:38:30

标签: r dplyr

假设您已按照以下步骤重新使用了以下数据框:

df= data.frame(id1= c(1,1,1,1,1,2,2,2,2,2), name =c("a","a","b","b","c","a","a","d","d","b"), name2 = c(NA,NA,"a",NA,"c",   "d","a","b",NA,NA))
df = df %>% group_by(id1) %>% summarise(name =name %>% unique %>% toString, name2= name2%>% unique %>% toString) 
df = as.data.frame(df)
df = df %>%mutate(name = strsplit(name, ", "), name2 = strsplit(name2, ", "))

生成的df将用于创建新列,其中逐行获取namename2的交集,在每一行中,我都不关心namename2

中元素的顺序

这是我尝试过的,但这只是我的第一个要素

library(purrr)
inter = rep("", length(df$name))
for (row in c(1:length(df$name)))  {
    print(row)
    inter[[row]] = ifelse(purrr::is_empty(intersect(df$name[[row]],df$name2[[row]])),
                    NA,intersect(df$name[[row]],df$name2[[row]]))
}

1 个答案:

答案 0 :(得分:2)

一个选择是map2遍历相应的list('name','name2')并在新的intersect中获得list个元素列

library(tidyverse)
df %>%
    mutate(newCol = map2(name, name2, intersect))