【问题标题】:reshape R data frame long to wide [duplicate]将R数据框从长到宽[重复]
【发布时间】:2021-11-30 12:47:30
【问题描述】:

我正在尝试将我的数据从长调整为宽

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 添加到列中

【问题讨论】:

  • 你能解释一下你是如何获得第一个元素 0.322 的吗?
  • 您能否包含set.seed 以使问题可重现?

标签: r dataframe reshape data-manipulation


【解决方案1】:

您可以使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-03
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多