【问题标题】:Reshaping a data.frame in R在 R 中重塑 data.frame
【发布时间】:2013-12-19 13:52:17
【问题描述】:

我得到了一个温度数据框:我在每一天的每一天都以摄氏度为单位测量温度,所以我得到了一个这样的 csv 文件:

   Day     Hour Temperature
11/10/2013  9:00    6
11/10/2013  10:00   11
11/10/2013  11:00   13
11/10/2013  12:00   6
11/10/2013  13:00   8
12/10/2013  9:00    7
12/10/2013  10:00   8
12/10/2013  11:00   11
12/10/2013  12:00   18
12/10/2013  13:00   12
13/10/2013  9:00    15
13/10/2013  10:00   8
13/10/2013  11:00   11
13/10/2013  12:00   16
13/10/2013  13:00   9

我正在尝试在 R 中对其进行重新排序,以获取每天更改标题文本的记录:

  Day       9:00   10:00 11:00 12:00 13:00
11/10/2013    6      11    13    6     8
12/10/2013    7       8    11   18    12
13/10/2013   15       8    11   16     9

我尝试了 cbind、sapply 和 unique 的几种组合,但我不知道它们是否是对我的 data.frame 重新排序的正确 R 元素。任何想法,建议? 非常感谢

【问题讨论】:

  • 查看reshape2包中的函数dcast
  • @user2261983 查看我的回答,了解在您提出问题时向其他人提供数据的有用方法。使用dput(my_data) 是另一种选择。

标签: r dataframe reshape


【解决方案1】:

这是您的数据作为数据框。

temperatures <- read.table(
  text = "   Day     Hour Temperature
  11/10/2013  9:00    6
  11/10/2013  10:00   11
  11/10/2013  11:00   13
  11/10/2013  12:00   6
  11/10/2013  13:00   8
  12/10/2013  9:00    7
  12/10/2013  10:00   8
  12/10/2013  11:00   11
  12/10/2013  12:00   18
  12/10/2013  13:00   12
  13/10/2013  9:00    15
  13/10/2013  10:00   8
  13/10/2013  11:00   11
  13/10/2013  12:00   16
  13/10/2013  13:00   9",
  header = TRUE
)

这是 Roland 建议的解决方案,使用 dcast

library(reshape2)
dcast(temperatures, Day ~ Hour, value.var = "Temperature")

仅供参考,您是在“重塑”数据,而不是“重新排序”数据(这意味着更改行顺序但保持列不变;为此使用 sortplyr::arrange)。


使用基础 R:

reshape(
  temperatures, 
  direction = "wide", 
  idvar     = "Day", 
  timevar   = "Hour", 
  v.names   = "Temperature"
)

【讨论】:

  • @JackRyan 您也可以使用 factor(Hour, levels = paste0(formatC(0:23, flag = "0", width = 2), ":00")) 手动重新调整因子。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 1970-01-01
  • 2012-06-23
相关资源
最近更新 更多