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
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
Thanks in advance!
To convert R List to Numeric value, use the combination of the unlist() function and as. numeric() function. The unlist() function in R produces a vector that contains all the atomic components.
We can use map_df
after converting to a 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
Or with bind_rows
bind_rows(myList)
# A tibble: 2 x 3
# file New Old
# <chr> <dbl> <dbl>
#1 ABC 21 42
#2 CDF 206 84
myList <- list(NULL, list(file = 'ABC', New = 21, Old = 42),
list(file = 'CDF', New = 206, Old = 84))
Something like (ls
is your list):
df <- data.frame(matrix(unlist(ls), ncol = max(lengths(ls)), byrow = TRUE))
If column names matter, then
names(df) <- names(ls[[which(lengths(ls)>0)[1]]])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With