Search code examples
rdataframecoercion

R coerce special column in a data frame #R


I'm looking to coerce a dataframe containing a special column (matrix or list) into a "regular" dataframe where the special column has been spreaded across many columns. My example :

df <- data.frame(x = 1:3, y = I(matrix(1:9, nrow = 3)))
str(df)
#> 'data.frame':    3 obs. of  2 variables:
#>  $ x: int  1 2 3
#>  $ y: 'AsIs' int [1:3, 1:3] 1 2 3 4 5 6 7 8 9

I would need to apply a function to df to return the following dataframe:

  x y1 y2 y3
1 1  1  4  7
2 2  2  5  8
3 3  3  6  9

'data.frame':   3 obs. of  4 variables:
 $ x : num  1 2 3
 $ y1: num  1 2 3
 $ y2: num  4 5 6
 $ y3: num  7 8 9

Thank you for your help


Solution

  • We can use

    out <- as.data.frame(do.call(cbind, df))