【问题标题】:Reshape one column to multiple columns in R在R中将一列重塑为多列
【发布时间】:2021-11-26 16:49:39
【问题描述】:

我有一个数据框,例如:

Groups COL1
G1     1
G2     3
G3     5
G1     7
G2     9
G3     11

我想将Groups 列为多个唯一列,例如:

       G1 G2 G3 
  1    1  3  5
  2    7  9  8

有人有想法吗?

如果有帮助,这里是玩具数据:

structure(list(Groups = c("G1", "G2", "G3", "G1", "G2", "G3"), 
    Col1 = c(1L, 3L, 5L, 7L, 9L, 11L)), class = "data.frame", row.names = c(NA, 
-6L))

【问题讨论】:

  • COL1 来自哪里?
  • 对这种类型感到抱歉
  • COL2 的 G1 值为 1 和 7。为什么在结果表中 [COL2,G1] 的值只有 1?值 7-12 去哪儿了?
  • 好吧抱歉,我用正确的数据更新了帖子。

标签: r dplyr reshape


【解决方案1】:

修改后,这里是dplyrtidyr 解决方案:

library(tidyverse)
df %>% 
  pivot_wider(names_from = Groups,
              values_from = Col1,
              values_fn = list) %>% 
  unnest(cols = c(G1,G2,G3))

输出:

     G1    G2    G3
  <int> <int> <int>
1     1     3     5
2     7     9    11

使用的数据:

df <- structure(list(Groups = c("G1", "G2", "G3", "G1", "G2", "G3"), 
    Col1 = c(1L, 3L, 5L, 7L, 9L, 11L)), class = "data.frame", row.names = c(NA, 
-6L))

【讨论】:

    【解决方案2】:

    另一个想法是:

    df %>%
      group_by(Groups) %>%
      mutate(index = row_number()) %>%
      pivot_wider(names_from = "Groups", values_from = "Col1")
    
    # A tibble: 2 x 4
      index    G1    G2    G3
      <int> <int> <int> <int>
    1     1     1     3     5
    2     2     7     9    11
    

    最后可以放弃index

    【讨论】:

      【解决方案3】:

      我们可以使用base R中的unstack

      unstack(df, Col1 ~ Groups)
        G1 G2 G3
      1  1  3  5
      2  7  9 11
      

      【讨论】: