使用两个列表中的公共信息创建矩阵

时间:2019-04-04 15:07:21

标签: r list dataframe sum

在这个问题中所示的玩具示例的相同结构中,我有两个大列表。

dput(head(list1)):

list(FEB_GAMES = c(GAME1 = c("Stan", "Kenny", "Cartman", "Kyle", 
"Butters"), GAME2 = c("Kenny", "Cartman", "Kyle", "Butters")), 
MAR_GAMES = c(GAME3 = c("Stan", "Kenny", "Cartman", "Butters"
), GAME4 = c("Kenny", "Cartman", "Kyle", "Butters")))

dput(head(list2)):

list(first = c("Stan", "Kenny", "Cartman", "Kyle", "Butters", 
"Kenny", "Cartman", "Kyle", "Butters"), second = c("Stan", "Kenny", 
"Cartman", "Wendy", "Ike"), third = c("Randy", "Randy", "Randy", 
"Randy"))

我想将这两个列表变成一个大的data.frame /矩阵。行名将来自列表1(GAME1,GAME2,GAME3,GAME4)。别名将是列表2(第一,第二,第三)的列表名称。矩阵中的信息将是一个整数,它表示在两个列表中找到一个公共字符的次数。例如GAME1xfirst包含9个常见字符,而GAME1xthird包含0个常见字符。


输出看起来像这样:

        first  second  third
GAME1   9      3       0
GAME2   8      2       0
GAME3   8      3       0
GAME4   8      2       0

因此[1,1]中的值将是在列表1的GAME1列表和列表2中的第一个列表中找到一个公共字符的时间之和。

注意。列表1和列表2中的列表具有不同数量的值。

2 个答案:

答案 0 :(得分:2)

一种选择是先展平'list1',转换为merge后再做data.frame,然后再做table

list1a <- do.call(c, list1)
names(list1a) <- sub(".*\\.", "", names(list1a))
out <- table(merge(stack(list1a), stack(list2), by = 'values')[-1])
names(dimnames(out)) <- NULL
out
#      first second third
#GAME1     9      3     0
#GAME2     8      2     0
#GAME3     7      3     0
#GAME4     8      2     0

我们也可以在tidyverse中使用相同的逻辑

library(tidyverse)
list1 %>% 
    flatten %>% 
    enframe %>% 
    unnest %>% 
    full_join(list2 %>% 
                enframe %>%
                unnest, by = 'value') %>% 
    select(-value) %>% 
    count(name.x, name.y) %>% 
    spread(name.y, n, fill = 0) %>%
    filter(!is.na(name.x))
# A tibble: 4 x 4   
#  name.x first second third
#  <chr>  <dbl>  <dbl> <dbl>
#1 GAME1      9      3     0
#2 GAME2      8      2     0
#3 GAME3      7      3     0
#4 GAME4      8      2     0

数据

list1 <- list(FEB_games = list(GAME1 = c("Stan", "Kenny", "Cartman", "Kyle", 
"Butters"), GAME2 = c("Kenny", "Cartman", "Kyle", "Butters")), 
MAR_games = list(GAME3 = c("Stan", "Kenny", "Cartman", "Butters"
), GAME4 = c("Kenny", "Cartman", "Kyle", "Butters")))

list2 <- list(first = c("Stan", "Kenny", "Cartman", "Kyle", "Butters", 
 "Kenny", "Cartman", "Kyle", "Butters"), second = c("Stan", "Kenny", 
 "Cartman", "Wendy", "Ike"), third = c("Randy", "Randy", "Randy", 
"Randy"))

答案 1 :(得分:2)

怎么样...

sapply(l2, function(x) {
  sapply(unlist(l1, recursive = FALSE), function(y) sum(x %in% y))
})
#                 first second third
# FEB_games.GAME1     9      3     0
# FEB_games.GAME2     8      2     0
# MAR_games.GAME3     7      3     0
# MAR_games.GAME4     8      2     0

不过,它可能不是最有效的方法。