重塑 R 数据框长到宽

reshape R data frame long to wide

我正在尝试将我的数据从长改成宽

set.seed(1)
y <- rnorm(12, 0, 1)
x <- rep(c("A","B"), each=6)
g <- rep(c("g1", "g2"), each=3)
t <-  rep(c(1,2,3), times=4)
df <- data.frame(y=y, x=x, g=g, t=t)

这就是我希望得到的:

    A.1     A.2     A.3    B.1     B.2     B.3
g1  -0.626  0.183  -0.835  0.487   0.738   0.575
g2  1.595   0.329  -0.820  -0.305  1.511   0.389

我试过 reshape

reshape(df, idvar = "g", timevar = "t", direction = "wide")

但我不知道如何将 x 添加到列

您可以使用 pivot_wider。此外,我使用 expand.grid.

添加了更紧凑的玩具数据集形式
library(tidyr)

df <- data.frame(y=y, expand.grid(t=c(1,2,3), g=c("g1", "g2"), x=c("A","B")))
pivot_wider(df, values_from = y, names_from = c(x,t), names_sep = ".")

  g        A.1   A.2    A.3    B.1   B.2   B.3
  <fct>  <dbl> <dbl>  <dbl>  <dbl> <dbl> <dbl>
1 g1    -0.626 0.184 -0.836  0.487 0.738 0.576
2 g2     1.60  0.330 -0.820 -0.305 1.51  0.390