R Split a column containing a vector into multiple

2019-07-27 09:49发布

问题:

Is it possible to split a column containing vectors with 3 elements into 3 seperate columns inside of a dataframe??

One column containing vectors like c("aa","bb","cc") should turn into 3 columns containing singular values like

"aa" "bb" "cc"

Every tidyr or dyplr operation that claims to do this only works on strings and formats the contents of my colum as the String "c("aa","bb","cc")" (?!) before splitting.

Is there any library that can split vectors into seperate columns?

回答1:

Here's one solution using dplyr and tidyr:

library(dplyr)
library(tidyr)

df %>% 
  unnest(a) %>% 
  group_by(id) %>% 
  mutate(key = row_number()) %>% 
  spread(key, a)

# A tibble: 2 x 4
# Groups: id [2]
     id `1`   `2`   `3`  
* <dbl> <chr> <chr> <chr>
1  1.00 aa    bb    cc   
2  2.00 aa    bb    cc   

Using data, provided by Florian:

df <- data.frame(
  id = c(1,2),
  a = I(list(c("aa", "bb", "cc"), c("aa", "bb", "cc")))
  )


标签: r vector