假设您已按照以下步骤重新使用了以下数据框:
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
将用于创建新列,其中逐行获取name
和name2
的交集,在每一行中,我都不关心name
和name2
这是我尝试过的,但这只是我的第一个要素
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]]))
}
答案 0 :(得分:2)
一个选择是map2
遍历相应的list
('name','name2')并在新的intersect
中获得list
个元素列
library(tidyverse)
df %>%
mutate(newCol = map2(name, name2, intersect))