【问题标题】:Transpose Rows in batches to Columns in R将行批量转置到 R 中的列
【发布时间】:2020-05-09 13:10:58
【问题描述】:

我的 data.frame df 看起来像这样:

A 1  
A 2  
A 5  
B 2  
B 3  
B 4  
C 3  
C 7  
C 9  

我希望它看起来像这样:

A B C  
1 2 3  
2 3 7  
5 4 9  

我已经尝试过spread(),但可能方法不对。有什么想法吗?

【问题讨论】:

    标签: r tidyr spread


    【解决方案1】:

    我们可以从base R使用unstack

    unstack(df1, col2 ~ col1)
    #  A B C
    #1 1 2 3
    #2 2 3 7
    #3 5 4 9
    

    split

    data.frame(split(df1$col2, df1$col1))
    

    或者如果我们使用spreadpivot_wider,请确保创建一个序列列

    library(dplyr)
    library(tidyr)
    df1 %>%
      group_by(col1) %>%
      mutate(rn = row_number()) %>%
      ungroup %>%
      pivot_wider(names_from = col1, values_from = col2) %>%
      # or use
      # spread(col1, col2) %>%
      select(-rn)
    # A tibble: 3 x 3
    #      A     B     C
    #  <int> <int> <int>
    #1     1     2     3
    #2     2     3     7
    #3     5     4     9
    

    或使用dcast

    library(data.table)
    dcast(setDT(df1), rowid(col1) ~ col1)[, .(A, B, C)]
    

    数据

    df1 <- structure(list(col1 = c("A", "A", "A", "B", "B", "B", "C", "C", 
    "C"), col2 = c(1L, 2L, 5L, 2L, 3L, 4L, 3L, 7L, 9L)),
       class = "data.frame", row.names = c(NA, 
    -9L))
    

    【讨论】:

      【解决方案2】:

      data.table,我们可以使用dcast

      library(data.table)
      dcast(setDT(df), rowid(col1)~col1, value.var = 'col2')[, col1 := NULL][]
      
      #   A B C
      #1: 1 2 3
      #2: 2 3 7
      #3: 5 4 9
      

      【讨论】:

        猜你喜欢
        • 2013-07-27
        • 1970-01-01
        • 1970-01-01
        • 2023-04-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-04
        • 2014-10-12
        相关资源
        最近更新 更多