How can I stack columns per x columns in R

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

    A classical split-apply-combine approach will scale flexibly:

    as.data.frame(lapply(split(unclass(df), 
                               names(df)[seq(ncol(df) / 2)]), 
                         unlist, use.names = FALSE))
    ##   A  B
    ## 1 1  4
    ## 2 2  5
    ## 3 3  6
    ## 4 7 10
    ## 5 8 11
    ## 6 9 12
    

    or with a hint of purrr,

    library(purrr)
    
    df %>% unclass() %>%    # convert to non-data.frame list
        split(names(.)[seq(length(.) / 2)]) %>%     # split columns by indexed names
        map_df(simplify)    # simplify each split to vector, coerce back to data.frame
    ## # A tibble: 6 × 2
    ##       A     B
    ##    
    ## 1     1     4
    ## 2     2     5
    ## 3     3     6
    ## 4     7    10
    ## 5     8    11
    ## 6     9    12
    

提交回复
热议问题