我正在尝试使用不同基数的%更改来重建此变量。我希望基数从5开始,使用colunmn 2中的百分比变化,有没有办法在不使用循环的情况下构建变量?
我在R中使用以下代码但收效甚微:
data$intial=lag(data$intial,-1)*(data$pctchng)
Error: is.numeric(x) is not TRUE
ratio pctchng initial
1.005028571 NA 5
1.006367978 0.133270514 NA
1.00566508 -0.069845001 NA
1.010365029 0.467347325 NA
1.013941983 0.354025918 NA
1.007602862 -0.625195643 NA
1.004898686 -0.268377165 NA
1.005610413 0.070825714 NA
1.00494049 -0.066618579 NA
1.007815989 0.286136319 NA
答案 0 :(得分:2)
> cumprod(c(5, tail(data$pctchng, -1) + 1))
## [1] 5.000000 5.666353 5.270586 7.733781 10.471739 3.924854 2.871512
## [8] 3.074889 2.870045 3.691269
或
> cumprod(c(5, tail(data$pctchng, -1)/100 + 1))
## [1] 5.000000 5.006664 5.003167 5.026549 5.044344 5.012807 4.999354 5.002895
## [9] 4.999562 5.013867
给出与vaettchen相同的答案。取决于你如何定义pctchng
答案 1 :(得分:1)
这是否会产生您的意思:
data$idx <- data$ratio / data$ratio[ 1 ]
data$initial <- data$idx * 5
data
ratio pctchng initial idx
1 1.005029 NA 5.000000 1.0000000
2 1.006368 0.13327051 5.006664 1.0013327
3 1.005665 -0.06984500 5.003167 1.0006333
4 1.010365 0.46734732 5.026549 1.0053098
5 1.013942 0.35402592 5.044344 1.0088688
6 1.007603 -0.62519564 5.012807 1.0025614
7 1.004899 -0.26837716 4.999354 0.9998708
8 1.005610 0.07082571 5.002895 1.0005789
9 1.004940 -0.06661858 4.999562 0.9999124
10 1.007816 0.28613632 5.013867 1.0027735