質問

I have approximately the following df :

a  <- seq(1, 1010, 1)
b  <- seq(2,1011,1)
c  <- c(rep(1,253), rep(2, 252), rep(3,254), rep(4,251))
d  <- c(rep(5,253), rep(6, 252), rep(7,254), rep(8,251))
df <- data.frame(a,b,c,d)

Firstly I grouped my date by columns c and d. Now I want to calculate simple returns. I apply the following code:

 df1<-dlply( df, .(c,d) , transform, simplereturn=c(NA,df[2:length(a),"a"]/df[1:(length(a)-1),"a"]) )
 df<-do.call("rbind", df1)

It seems it does not work properly and moreover, I would like to make calculations using data.table approach. Any suggestions? Thank you for attention

役に立ちましたか?

解決

Here is what I assume to be the correct plyr solution:

df <- ddply( df, .(c,d) , transform, simplereturn=c(NA, a[-1] / head(a, -1)))

And here the equivalent data.table code:

library(data.table)
setDT(df)
df[, simplereturn := c(NA, a[-1] / head(a, -1)), by=list(c, d)]
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top