How can I stack columns per x columns in R

前端 未结 5 624
春和景丽
春和景丽 2021-01-07 14:25

I\'m looking to transform a data frame of 660 columns into 3 columns just by stacking them on each other per 3 columns without manually re-arranging (since I have 660 column

5条回答
  •  失恋的感觉
    2021-01-07 14:49

    Here is another base R option

    i1 <- c(TRUE, FALSE)
    `row.names<-`(data.frame(A= unlist(df1[i1]), B = unlist(df1[!i1])), NULL)
    #  A  B
    #1 1  4
    #2 2  5
    #3 3  6
    #4 7 10
    #5 8 11
    #6 9 12
    

    Or another option is melt from data.table

    library(data.table)
    i1 <- seq(1, ncol(df1), by = 2)
    i2 <- seq(2, ncol(df1), by = 2)
    melt(setDT(df1), measure = list(i1, i2), value.name = c("A", "B"))
    

提交回复
热议问题