I have a list of list as given below. ANd I want to convert it into dataframe in the desired format.
myList:
[[1]]
NULL
[[2]]
[[2]]$`file`
[1] "ABC"
[[2]]$New
[1] 21
[[2]]$Old
[1] 42
[[3]]
[[3]]$`file`
[1] "CDF"
[[3]]$NEW
[1] 206
[[3]]$Old
[1] 84
Run Code Online (Sandbox Code Playgroud)
And I want to convert this list of list object to dataframe in the desired format:
file New Old
ABC 21 42
CDF 206 84
Run Code Online (Sandbox Code Playgroud)
Thanks in advance!
akr*_*run 13
我们可以map_df在转换为一个后使用tibble
library(tidyverse)
myList %>%
map_df(as_tibble)
# A tibble: 2 x 3
# file New Old
# <chr> <dbl> <dbl>
#1 ABC 21 42
#2 CDF 206 84
Run Code Online (Sandbox Code Playgroud)
或与 bind_rows
bind_rows(myList)
# A tibble: 2 x 3
# file New Old
# <chr> <dbl> <dbl>
#1 ABC 21 42
#2 CDF 206 84
Run Code Online (Sandbox Code Playgroud)
myList <- list(NULL, list(file = 'ABC', New = 21, Old = 42),
list(file = 'CDF', New = 206, Old = 84))
Run Code Online (Sandbox Code Playgroud)
像(ls是你的清单):
df <- data.frame(matrix(unlist(ls), ncol = max(lengths(ls)), byrow = TRUE))
Run Code Online (Sandbox Code Playgroud)
如果列名很重要,那么
names(df) <- names(ls[[which(lengths(ls)>0)[1]]])
Run Code Online (Sandbox Code Playgroud)
It looks like the following would work.
do.call(rbind, lapply(list, as.data.frame))
Run Code Online (Sandbox Code Playgroud)
where list is your list.