Combining subscriptions of different lists into a list of data blocks

I have a large number of lists, each of which consists of many subscriptions. Each list contains a sub-list in which each sub-list will have the same name and the number of observations in different lists.

Here is a simple data example:

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'))) 

I am looking to create a list of data frames that combine sub-lists together and store names.

 my.list.Bob score comments 1 AAA 0 BBB my.list.Jane score comments 1 ZZZ 2 XXX 4 YYY 2 QQQ 
+5
source share
2 answers

Here is one way for you. If you have all the listings in your global environment, you can do the following. First you create a list with all the lists you have. Then you use transpose() , which allows you to create a list for each person (for example, a list for Bob with rating and comments). In each list, you have comments and ratings as nested lists in this case. You want to list them in each list. For this reason, you can use rapply2() by rawr. Finally, you create a data frame for each list.

 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 
+3
source

Solution using . The idea is to use a map2 through each item from two lists, use map_dfr and as_data_frame to create a data frame, and then use bind_cols to combine each data frame.

 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 
+2
source

Source: https://habr.com/ru/post/1276278/


All Articles