0

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?

talat
  • 68,970
  • 21
  • 126
  • 157
adriansteffan
  • 41
  • 1
  • 3
  • All columns in a data frame are vectors, and `tidyr::spread` works to turn long columns into wide columns for any atomic data type. Are you perhaps referring to a list column wherein each element is a vector? Please add example data to clarify. See: https://stackoverflow.com/q/5963269/8262231 – W. Murphy Jan 12 '18 at 15:47
  • I'm not sure I fully understand, but if you have a vector `MyVect <- c("aa","bb","cc")`, you wish to convert into columns then you could use `data.frame(t(MyVect))`. – Dan Jan 12 '18 at 15:50
  • 3
    `cbind(df, do.call(rbind, df$a))` would be an option – talat Jan 12 '18 at 16:08

1 Answers1

7

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")))
  )
tyluRp
  • 4,678
  • 2
  • 17
  • 36