【问题标题】:Reshaping data from long to wide format in R [duplicate]在R中将数据从长格式重塑为宽格式[重复]
【发布时间】:2017-01-25 15:00:51
【问题描述】:

我有一个数据集如下图:

Frame  | X.axis | Y.axis | Z.axis
-------|--------|--------|--------
  1    |  0.2   |  0.215 |  0.965
-------|--------|--------|--------
  2    |  0.54  |  1.25  | 2.219
-------|--------|--------|--------
  1    |  2.124 |  2.418 |  1.35
-------|--------|--------|--------
  2    |  -1.2  |  0.49  | 1.87
-------|--------|--------|--------
  1    |  6.42  |  -1.28 |  7.1
-------|--------|--------|--------
  2    |  6.45  |  -2.5  | 8.5

我想将上表改造成如下所示:

frame1.X.axis  | frame1.Y.axis | frame1.Z.axis | frame2.X.axis  | frame2.Y.axis | frame2.Z.axis
--------|--------|--------|--------|--------|--------
  0.2   |  0.215 |  0.965 |  0.54  |  1.25  | 2.219
--------|--------|--------|--------|--------|--------
  2.124 |  2.418 |  1.35  |  -1.2  |  0.49  | 1.87
--------|--------|--------|--------|--------|--------
  6.42  |  -1.28 |  7.1   |  6.45  |  -2.5  | 8.5

上述任务如何实现?

重要提示

真实数据集有 16 帧而不是 2。要传播的列是 90 而不是 3。所以我不想要一个需要我手动提及新列名的函数。我希望函数以某种方式自动命名列名。

我尝试过使用tidyr 包的spread 函数,但我无法使用它。然后我尝试了reshape 函数,但它也要求提供新的列名。

【问题讨论】:

  • 请参阅this Q/A 以提供可重现的数据。

标签: r reshape reshape2 tidyr


【解决方案1】:

你可以试试:

# some data
set.seed(123)
df <- data.frame(matrix(c(rep(1:2,3), runif(18)), byrow = F,6,4))
colnames(df) <- c("Frame", "X.axis", "Y.axis", "Z.axis")
df
Frame    X.axis    Y.axis     Z.axis
1     1 0.2875775 0.5281055 0.67757064
2     2 0.7883051 0.8924190 0.57263340
3     1 0.4089769 0.5514350 0.10292468
4     2 0.8830174 0.4566147 0.89982497
5     1 0.9404673 0.9568333 0.24608773
6     2 0.0455565 0.4533342 0.04205953

library(reshape2)
# transform to long
df1 <- melt(df, measure.vars = colnames(df)[-1])
# order
df1 <- df1[order(df1$Frame), ]
# add suitable columns for transformation
# Following code adds a continuous number per "Frame" level
df1$New <- ave(as.numeric(df1$variable), interaction(df1$variable,  df1$Frame), FUN = seq_along)
# The new column name
df1$New2 <- paste0("Frame", df1$Frame, ".", df1$variable)
# long format
dcast(df1, New ~ New2, value.var = "value")
New Frame1.X.axis Frame1.Y.axis Frame1.Z.axis Frame2.X.axis Frame2.Y.axis Frame2.Z.axis
1   1     0.2875775     0.5281055     0.6775706     0.7883051     0.8924190    0.57263340
2   2     0.4089769     0.5514350     0.1029247     0.8830174     0.4566147    0.89982497
3   3     0.9404673     0.9568333     0.2460877     0.0455565     0.4533342    0.04205953

【讨论】:

  • df$New 代码在这里做什么?请解释整个代码行。我理解所有其他代码。
  • 在这种情况下,一种简单的 split-apply-combine 方法也可以工作:do.call(cbind, split(df[-1], df$Frame))
  • @lmo 真的很优雅!竖起大拇指。
猜你喜欢
  • 2020-10-23
  • 1970-01-01
  • 2022-07-28
  • 1970-01-01
  • 2015-08-04
  • 2021-09-15
  • 2021-08-27
  • 1970-01-01
  • 2022-01-11
相关资源
最近更新 更多