user6890504 user6890504 - 2 months ago 6
R Question

how to split one column into multiple?

I have a data frame with two rows and one column. I would like to split one column into eight columns.

Input:

V1
1 Source Model terms Gamma Component Comp/SE % C
2 animal 10600 10600 0.336134 0.266547 14.26 0 P


I like this output:

V1 V2 V3 V4 V5 V6 V7 V8
1 Source Model terms Gamma Component Comp/SE % C
2 animal 10600 10600 0.336134 0.266547 14.26 0 P

Answer

Here's one possible solution. Consider df is your data.frame:

> output <- data.frame(t(apply(df, 1, function(x) unlist(strsplit(x, "[[:space:]]+")))))
> names(output) <- paste0("V", 1:8)
> output
      V1    V2    V3       V4        V5      V6 V7 V8
1 Source Model terms    Gamma Component Comp/SE  %  C
2 animal 10600 10600 0.336134  0.266547   14.26  0  P
Comments