我有一个数据框架,如:
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))
编辑完成后,dplyr
和tidyr
的解决方案如下:
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
我们可以从base R
中使用unstack
unstack(df, Col1 ~ Groups)
G1 G2 G3
1 1 3 5
2 7 9 11