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.
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)