[英]transform list of lists to dataframes of list where sub lists have different number of rows
[英]Combine sub lists of different lists into a list of dataframes
我有大量的列表,每個列表都包含許多子列表。 每個列表都包含一個子列表,其中每個子列表在不同列表中具有相同的名稱和觀察數量。
這是一個簡單的數據示例:
score <- list(Bob = list(c('1'), ('0')), Jane = list(c('1'), ('2'), ('4'), ('2')))
comments <- list(Bob = list(c('AAA'), ('BBB')), Jane = list(c('ZZZ'), ('XXX'), ('YYY'), ('QQQ')))
我希望創建一個數據框列表,將子列表組合在一起並保留名稱。
my.list.Bob
score comments
1 AAA
0 BBB
my.list.Jane
score comments
1 ZZZ
2 XXX
4 YYY
2 QQQ
這是給你的一種方式。 如果您在全局環境中擁有所有列表,則可以執行以下操作。 首先,創建一個包含所有列表的列表。 然后,您使用transpose()
,它允許您為每個人創建一個列表(例如,Bob的評分和評論列表)。 在每個列表中,在這種情況下,您有評論和得分作為嵌套列表。 您想要在每個列表中取消列表。 因此,您可以使用rawr的rapply2()
。 最后,為每個列表創建一個數據框。
library(magrittr)
library(purrr)
library(rawr) #devtools::install_github('raredd/rawr')
score <- list(Bob = list(c('1'), ('0')), Jane = list(c('1'), ('2'), ('4'), ('2')))
comments <- list(Bob = list(c('AAA'), ('BBB')), Jane = list(c('ZZZ'), ('XXX'), ('YYY'), ('QQQ')))
# Get all objects in the global environment and create a list.
mylist <- mget(ls(pattern = ".*"))
purrr::transpose(mylist) %>%
rapply2(unlist, classes = "list") %>%
lapply(as.data.frame, stringsAsFactors = FALSE)
$Bob
comments score
1 AAA 1
2 BBB 0
$Jane
comments score
1 ZZZ 1
2 XXX 2
3 YYY 4
4 QQQ 2
使用tidyverse的解決方案。 我們的想法是使用map2
循環遍歷兩個列表中的每個元素,使用map_dfr
和as_data_frame
創建數據框,然后使用bind_cols
組合每個數據框。
library(tidyverse)
map2(score, comments, function(x, y){
X <- map_dfr(x, as_data_frame)
Y <- map_dfr(y, as_data_frame)
dat <- bind_cols(X, Y) %>%
set_names(c("score", "comments"))
})
# $Bob
# # A tibble: 2 x 2
# score comments
# <chr> <chr>
# 1 1 AAA
# 2 0 BBB
#
# $Jane
# # A tibble: 4 x 2
# score comments
# <chr> <chr>
# 1 1 ZZZ
# 2 2 XXX
# 3 4 YYY
# 4 2 QQQ
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.