简体   繁体   中英

R list of intersection of lists

Suppose you are handed the following dataframe reuslting of the following steps:

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, ", "))

The resulting df is to be used to create a new column, where row by row gets the intersection of name and name2 , where within each row, I do not care about the order of elements in name and name2

Here is what I tried , it only gets me the first element however

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]]))
}

One option is map2 to loop over the corresponding list s ('name', 'name2') and get the intersect ion of elements in a new list column

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM