Home > Software engineering >  make a dataframe out of a list of uneven-length numeric vectors adding an ID column
make a dataframe out of a list of uneven-length numeric vectors adding an ID column

Time:10-07

I have a long list of vectors:

mylist <- list(a = c(1,2,3)
               ,b = c(2,3)
               )

I would like to combine these vectors into a single two-column dataframe, where the first column (named sd) stores the vector content, and the second column (named id) stores the vector ID. The final dataframe should look as follows:

    sd id
1    1  a
2    2  a
3    3  a
4    2  b
5    3  b

I imagined that bind_rows(mylist, .id = "id") would do the job, but I get the Tibble columns must have compatible sizes. error.

CodePudding user response:

Using tidyr and tibble :

library(tibble)
library(tidyr)    
enframe(mylist,name="id",value="sd") %>% unnest(sd)
    # A tibble: 5 × 2
      id       sd
      <chr> <dbl>
    1 a         1
    2 a         2
    3 a         3
    4 b         2
    5 b         3

enframe converts named atomic vectors or lists to one- or two-column data frame and unnest makes each element of sd on its own row

CodePudding user response:

You can do this with pivot_longer:

library(tidyr)
data.frame(t(mylist)) %>%
  pivot_longer(1:2) %>% unnest(1:2)
# A tibble: 5 × 2
  name  value
  <chr> <dbl>
1 a         1
2 a         2
3 a         3
4 b         2
5 b         3
  • Related