Reputation: 5169
I have the following nested list:
l <- list(`1` = c(Fn1 = 85.3820037423659, Sema3c = 0.0362596376899117,
App = 8.08423415658745), `3` = c(Fn1 = 11.0051859200698, Sema3c = 0,
App = 44.0000000000306), `4` = c(Fn1 = 3.4594316186373, Sema3c = 0,
App = 6.54280428377643))
That looks like this:
$`1`
Fn1 Sema3c App
85.38200374 0.03625964 8.08423416
$`3`
Fn1 Sema3c App
11.00519 0.00000 44.00000
$`4`
Fn1 Sema3c App
3.459432 0.000000 6.542804
What I want to convert them into tibble.
`1` `3` `4`
Fn1 85.4 11.0 3.46
Semac3 0.0363 0 0
App 8.08 44. 6.54
How can I achieve that?
I tried tibble::as_tibble(l)
but it doesn't show the row name.
Upvotes: 0
Views: 621
Reputation: 886948
We can use unnest_wider
library(tidyr)
library(purrr)
tibble(col1 = map(l, as.list)) %>%
unnest_wider(col1) %>%
t
Or using transpose
from purrr
and map
library(tibble)
transpose(l) %>%
map_df(~ .x, .id = 'grp') %>%
column_to_rownames('grp')
# 1 3 4
#Fn1 85.38200374 11.00519 3.459432
#Sema3c 0.03625964 0.00000 0.000000
#App 8.08423416 44.00000 6.542804
Upvotes: 1
Reputation: 388817
Here is one way with tidyverse
. Since we have a numeric vector in the list we first convert it into a tibble, combine the list of tibbles into one dataframe using bind_rows
, get the data in long format, bring it back to wide format changing the column names and turn the name
column to rownames.
library(tidyverse)
map(l, ~as_tibble(t(.x))) %>%
bind_rows(.id = 'id') %>%
pivot_longer(cols = -id) %>%
pivot_wider(names_from = id, values_from = value) %>%
column_to_rownames('name')
# 1 3 4
#Fn1 85.3820 11 3.46
#Sema3c 0.0363 0 0.00
#App 8.0842 44 6.54
Upvotes: 1