vol=list() ;df=data.frame(name=c(5,2,15,4),name=c(2,0,1,2))
vol[[1]] <- dplyr::lst(!! names(df)[1] := df)
df2=data.frame(dat=c(5,2,15,4),dat=c(2,0,1,2))
vol[[2]] <- dplyr::lst(!! names(df2)[1] := df2)
How to convert this list (vol) to adata frame like this:
A Par var
name 5 2
name 2 0
name 15 1
name 4 2
dat 5 2
dat 2 0
dat 15 1
dat 4 2
CodePudding user response:
We may need to modify the column names in the list
to commmon names ('Par', 'var') before binding them with map_dfr
. As it is a nested list
, (flatten
first if it is a nested list) and then do the changes. If we need the inner list name as column, use the .id
to create the column with the list names
library(dplyr)
library(purrr)
vol2 %>%
map_dfr(~ .x %>% rename_all(~ c("Par", "var")), .id = "A")
-output
A Par var
1 name 11 17
2 name 23 12
3 name 94 123
4 name 32 11
5 name 7 117
6 B.Ch 11 10
7 B.Ch 96 10
8 B.Ch 8 10
9 B.Ch 68 133
10 B.Ch 5 1167
Or using the same method in base R
, flatten with c
, loop over the list
with lapply
to rename, then create a column with Map
and cbind
and finally rbind
the list
elements
lst1 <- lapply(vol2, setNames, c("Par", "var"))
dat <- do.call(rbind, Map(cbind, A = names(lst1), lst1))
row.names(dat) <- NULL
-output
> dat
A Par var
1 name 11 17
2 name 23 12
3 name 94 123
4 name 32 11
5 name 7 117
6 B.Ch 11 10
7 B.Ch 96 10
8 B.Ch 8 10
9 B.Ch 68 133
10 B.Ch 5 1167
data
vol2 <- list(name = structure(list(name = c(11, 23, 94, 32, 7), name.1 = c(17,
12, 123, 11, 117)), class = "data.frame", row.names = c(NA, 5L
)), B.Ch = structure(list(B.Ch = c(11, 96, 8, 68, 5), B.Ch.1 = c(10,
10, 10, 133, 1167)), class = "data.frame", row.names = c(NA,
5L)))