在 R 中将一列重塑为多列

Reshape one column to multiple columns in R

我有一个数据框,例如:

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))

编辑后,这里有一个 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))

另一个想法是:

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

我们可以使用 unstack 来自 base R

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