【问题标题】:Reshaping time series data from wide to long format将时间序列数据从宽格式重塑为长格式
【发布时间】:2015-09-19 21:23:40
【问题描述】:

给定四个客户端的时间序列数据,客户端 1、2、3、4。

names(data)
"Date" "X1.CLIENT"   "X1seasonal"  "X1trend"  "X1remainder" "X2.CLIENT" 
  "X2seasonal"  "X2trend"     "X2remainder" "X3.CLIENT"   "X3seasonal"  
"X3trend"     "X3remainder" "X4.CLIENT"   "X4seasonal"  "X4trend"     
"X4remainder"

请注意,每个客户数据后面都是同一时期的季节性、趋势和剩余部分。

我想以一种看起来像

的方式重塑为长格式
"Date" "CLIENT_Number" "Type"  "Value"

[Client_Number : 1,2,3,4 ;类型:客户、季节性、趋势、剩余]

(额外帮助理解:如果数据(宽格式)有 30 行/实例,那么我们必须转换为长格式(30*4*4= 480 行/实例)

【问题讨论】:

  • 您可以通过向我们展示一些实际数据并改进格式来改进这个问题。在完成之前,请务必查看预览,看看您的问题会是什么样子。
  • 我投票结束这个问题作为题外话,因为它只是一个微不足道的 R 编程问题,所以应该在 stackoverflow 上
  • 查看melt 包中的reshape2

标签: r time-series pivot-table


【解决方案1】:

看起来您的数据是一种尴尬的重复宽格式。正如 ssdecontrol 所说,使用 reshape2 中的 melt,我会结合 lapply 之类的东西来分割成多个部分。例如:

# Set up
install.packages("reshape2")
library(reshape2)

# Dummy data
d = data.frame(date=seq.Date(as.Date("2015-01-01"), length.out=100, by=1),
Client.1="A", trend.1=rnorm(100), remainder.1=rpois(10, 3), Client.2="B",
trend.2=rnorm(100), remainder.2=rpois(10, 3), Client.3="C", trend.3=rnorm(100),
remainder.3=rpois(10, 3))

# Split data by columns with client numbers
d = lapply(c(2,5,8), function(i){
    # Take columns relating to client i
    x = d[,c(1, seq(i, length.out=3, by=1))]
    # Rename so you have consistent factor labels
    names(x)[2:4] = c("client", "trend", "remainder")
    # Conververt from wide to long
    x = melt(x, id.vars=c("date", "client"))
})

# Make list into a data frame
d = do.call("rbind", d)

我发现这篇文章对宽格式和长格式非常清楚:http://seananderson.ca/2013/10/19/reshape.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2020-01-26
    相关资源
    最近更新 更多