r - List of dataframes, how can I group every nth element? -
let's have list of dataframes called old_list:
#old_list list of length 10 #create vectors dfs (there's concise way this). old_list<-list(rnorm(10),rnorm(10),rnorm(10),rnorm(10),rnorm(10),rnorm(10), rnorm(10),rnorm(10),rnorm(10),rnorm(10)) #turn old_list df; add second column library('dplyr') old_list<-lapply(old_list,function(x) as.data.frame(x)%>%mutate(mu=1)) ok, old_list looks this:
[[1]] x mu 1 -0.47734743 1 2 0.28986887 1 3 0.02933248 1 4 -2.15761840 1 5 0.32944305 1 6 0.33237442 1 7 -0.48621491 1 8 -0.61504793 1 9 -1.45353709 1 10 -1.22628027 1 [[2]] x mu 1 0.10329026 1 2 -0.43502662 1 3 0.87865194 1 4 -0.37628634 1 5 0.06234334 1 6 0.35441583 1 7 0.46176186 1 8 1.98786158 1 9 1.81183387 1 10 2.18143130 1 .... 10th element i want go grouping every nth df in old_list new list called new_list. let's want group every second df. new_listshould have list of length 5 every element should contain 2 dfs. i've tried code this:
new_list<-list() (i in 1:seq(1,length(old_list),2)){ new_list[[i]]<-list(old_list[i:i+1]) } but doesn't 'group' 1st , 2nd, 3rd , 4th, 5th , 6th... dfs old_list i'd like. tips?
this first element of new_list should (i didn't set seed ignore different values of rnorm(10):
list(c(old_list[1],old_list[2])) [[1]] [[1]][[1]] x mu 1 0.56877414 1 2 -2.35897500 1 3 1.16982547 1 4 -0.36609697 1 5 0.53758988 1 6 -1.05709000 1 7 -1.15997033 1 8 -0.07746139 1 9 -0.55179839 1 10 -0.11192844 1 [[1]][[2]] x mu 1 0.34540644 1 2 -0.14567340 1 3 -0.56627562 1 4 0.22785077 1 5 -1.73692747 1 6 -1.03707293 1 7 -0.32093204 1 8 0.09449727 1 9 0.41419075 1 10 -0.17093046 1
if need split list , nest elements based on 'n', use gl create grouping variable, split 'old_list' , convert tibble
library(tidyverse) n <- 2 map2(list(old_list), length(old_list), ~split(.x, as.integer(gl(.y, n, .y)))) %>% modify_depth(3, ~tibble(x = ., mu = 1)) or may this
n <- 2 res <- lapply(split(old_list, as.integer(gl(length(old_list), n, length(old_list)))), function(x) lapply(x, function(y) data.frame(x= y, mu = 1))) res[1] #$`1` #$`1`[[1]] # x mu #1 1.11696564 1 #2 -0.32362765 1 #3 0.07355866 1 #4 0.97178378 1 #5 0.55000016 1 #6 0.34958254 1 #7 1.32894403 1 #8 -1.02388909 1 #9 0.48285111 1 #10 -0.55077723 1 #$`1`[[2]] # x mu #1 -0.4506403 1 #2 0.8701737 1 #3 3.3360928 1 #4 1.4608549 1 #5 1.1038983 1 #6 2.3979434 1 #7 0.1652383 1 #8 0.2294786 1 #9 0.2031739 1 #10 -0.4322401 1
Comments
Post a Comment