简体   繁体   English

重塑前后宽->长->宽

[英]Reshape backandforth Wide -> long -> wide

I change my data to xts to do simple calculations, so I first reshape my data from long to wide, do my calculations and want to reshape it back. 我将数据更改为xts以进行简单的计算,因此我首先将数据从长到宽调整形状,进行计算并希望将其重新调整形状。

First my data looks like: 首先,我的数据如下所示:

          date seriesid       totret
1912-08-15    57409  0.000000000
1912-09-15    57409 -0.500000000
1912-10-15    57409  0.000000000
1912-11-15    57409  0.000000000
1912-12-15    57409  0.000000000
1913-01-15    57409  0.000000000
1913-02-15    57409  0.000000000
1913-03-15    57409  0.500000000
1913-04-15    57409 -0.250000000
1913-05-15    57409  0.000000000
1913-06-15    57409  0.000000000
1913-07-15    57409  0.000000000
1913-08-15    57409  0.000000000
1913-09-15    57409  0.000000000
1925-02-15    57746  0.001984127
1925-03-15    57746  0.049504950
1925-05-15    57746  0.190476190
1925-06-15    57746 -0.088333333
1925-08-15    57746  0.015384615
1925-09-15    57746  0.030303030

Then i recast it with: 然后我将其重铸为:

z <-reshape(PreCRSP, idvar="date", timevar = "seriesid", direction ="wide")
z <- as.data.table(z)
z <- as.xts.data.table(z)

port_rolling_sd_xts <- rollapply(z,FUN = sd,width = 36) 

Now I have the matrix below and want to transfer this back, how can I do this? 现在我有下面的矩阵,想把它转回去,我该怎么做?

index totret.57409 totret.57746 totret.55630 totret.55578
1824-01-15           NA           NA           NA           NA
1824-02-15           NA           NA           NA           NA
1824-03-15           NA           NA           NA           NA
1824-04-15           NA           NA           NA           NA
1824-05-15           NA           NA           NA           NA

I want this to be back in the format: 我希望它以以下格式返回:

date seriesid  sd
1912-08-15    57409  0.000000000
1912-09-15    57409 -0.500000000
1912-10-15    57409  0.000000000
1912-11-15    57409  0.000000000

answer was: 答案是:

sd <- tidyr::spread(Pre, key = "seriesid", value = "totret")
sd <- as.data.table(sd)
sd <- as.xts.data.table(sd)
sd <- rollapply(sd, FUN = sd, width = 36) 
sd <- as.data.table(sd)
SD <- tidyr::gather(sd, seriesid, sd, -index, na.rm=TRUE)
names(SD) <- c("date","seriesid","sd")
PreCRSPwithsd <- merge(Pre, SD, by=c("date", "seriesid"), all.x=TRUE)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM