Search code examples
rsplitdataframecol

Split one row after every 3rd column and transport those 3 columns as a new row in r


I have a data frame which is a result of another command. This data frame has only one row with around 40000 entries. My problem is that 3 columns are one connected set of data. Therefore I want to split the row after every third column and transport this as a new row. Example:

Create a test data frame:

df=as.data.frame(matrix(seq(1:12), ncol=12, nrow=1))

Now I have a data frame which looks like this.

V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12
1  2  3  4  5  6  7  8  9  10  11  12

But I need it like this:

V1 V2 V3
1  2  3
4  5  6
7  8  9
10 11 12

How can I realise this?


Solution

  • Try

    as.data.frame(matrix(unlist(df, use.names=FALSE),ncol=3, byrow=TRUE))
    #  V1 V2 V3
    #1  1  2  3
    #2  4  5  6
    #3  7  8  9
    #4 10 11 12
    

    Or you could directly use matrix on df

     as.data.frame(matrix(df, ncol=3, byrow=TRUE))