我试图在R中设置一个简单的for循环计算,从而用计算值填充数据。
这是它的要点:
价格(今天)=价格(昨天)* (1 +模拟回报(今天))
下面是一个示例:
## This makes a 30x10 dataframe of random simulated returns
ret = replicate(10, rnorm(30, mean = 0.1, sd = 0.25))
## This makes the empty 30x10 dataframe where prices will go
pri = ret
pri[] = NA
## This fills the first row of the second dataframe with given values (today's price)
given = replicate(10, 1234)
pri[1,] = given
在这之后,我遇到了设计一个正确的for-循环的问题。我不知道如何构造这个语法来使这个迭代,以便根据第一个dataframe中返回时间(t)的相应值和第二个dataframe中前一个时间段(t-1)的价格,使用上面描述的基本公式,对第二个dataframe中的每个空行逐一填充空单元格。
我想说的是
pri[2,] = pri[1,] * (1 + ret[2,])
但是对于第二个dataframe中的所有剩余行(第2:30行,按列分隔)。如有任何建议,将不胜感激。
发布于 2018-01-12 21:37:58
下面将介绍一种使用sapply
的基于函数的解决方案。逻辑是用模拟的回报因子填充价格矩阵,然后用今天的价格填充第一行。sapply
一次取1列,并根据该列的Price(today) = Price(yesterday) * (1 + Simulated Return(today))
和返回值执行计算,
## This makes a 30x10 dataframe of random simulated returns.
## Notice I have changed it to data.frame
ret = data.frame(replicate(10, rnorm(30, mean = 0.1, sd = 0.25))
## This makes the empty 30x10 dataframe where prices will go
pri = ret
## pri[] = NA -- no need. Let the factor be available for dates.
## This fills the first row of the second dataframe with given values (today's price)
given = replicate(10, 1234)
pri[1,] = given
# Function that performs calculation on simulated price based on previous day
poputate_value <- function(x){
for(i in 2:length(x)){
x[i] <- x[i-1] * (1 + x[i])
}
x
}
# Function will be applied on all columns and value will be returned to result
result <- sapply(pri, poputate_value)
## > head(result)
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
[1,] 1234.000 1234.000 1234.0000 1234.000 1234.0000 1234.000 1234.0000 1234.0000 1234.0000 1234.0000
[2,] 1038.855 1580.027 991.9454 1975.709 1447.9575 1733.466 856.0908 928.6600 1119.1489 1011.4543
[3,] 1113.040 1411.237 807.3748 1791.978 1333.1235 1957.516 972.3401 874.6964 1133.1161 1095.7755
[4,] 1242.637 1104.528 906.7417 1443.040 944.8004 2198.782 1242.2810 1314.4354 1722.6803 1478.0986
[5,] 1822.834 1224.279 1245.4425 1381.826 1295.5291 2887.676 1349.2818 1367.2311 908.4315 780.4360
[6,] 1690.193 1218.778 883.5074 2126.224 1340.3102 2994.756 1542.1661 1300.4834 998.1949 702.0578
https://stackoverflow.com/questions/48236596
复制相似问题