How can I stack columns per x columns in R

前端 未结 5 591
春和景丽
春和景丽 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:53

    rbindlist from data.table package can also be used for the task and seems to be much more efficient.

    # EXAMPLE DATA 
    df1 <- read.table(text = '
    Col1 Col2 Col3 Col4
    1    2    3    4
    5    6    7    8
    1    2    3    4
    5    6    7    8', header = TRUE)
    
    library(data.table)
    library(microbenchmark)
    library(purrr)
    microbenchmark(
        Map = as.data.frame(Map(c, df1[,1:2], df1[, 3:4])),
        Reshape = reshape(df1, direction="long", varying=split(names(df1), rep(seq_len(ncol(df1)/2), 2))),
        Purr = df1 %>% unclass() %>%    # convert to non-data.frame list
            split(names(.)[seq(length(.) / 2)]) %>%     # split columns by indexed names
            map_df(simplify), 
        DataTable = rbindlist(list(df1[,1:2], df1[, 3:4])),
        Mapply = data.frame(mapply(c, df1[,1:2], df1[, 3:4], SIMPLIFY=FALSE)),
        Rbind = rbind(df1[, 1:2],setnames(df1[, 3:4],names(df1[,1:2])))
    )
    

    The results are:

    Unit: microseconds
    expr     min         lq       mean         median     uq         max neval      cld
    Map        214.724   232.9380  246.2936    244.1240   255.9240   343.611    100  bc  
    Reshape    716.962   739.8940  778.7912    749.7550   767.6725   2834.192   100     e
    Purr       309.559   324.6545  339.2973    334.0440   343.4290   551.746    100    d 
    DataTable  98.228    111.6080  122.7753    119.2320   129.2640   189.614    100 a    
    Mapply     233.577   258.2605  271.1881    270.7895   281.6305   339.291    100   c  
    Rbind      206.001   221.1515  228.5956    226.6850   235.2670   283.957    100  b  
    

提交回复
热议问题