【问题标题】:Attempting to make a simple iterative calculation with a for loop in R尝试使用 R 中的 for 循环进行简单的迭代计算
【发布时间】:2018-01-13 03:11:02
【问题描述】:

我正在尝试在 R 中设置一个简单的 for 循环计算,从而用计算值填充数据框。

这里是它的要点:
- 我有一个 10 列宽和 30 行长的数据框;列是模拟收益的向量,行是一个月中的几天。
- 我有另一个相同大小的数据框,其中第一行是今天的股票价格,所有其他行都是空的。
- 我只是想使用给定的起始价格和第一个数据帧中的模拟收益迭代地填充第二个数据帧的其余部分,使用如下基本公式:

价格(今天) = 价格(昨天) * (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 循环时遇到了问题。我不确定如何构造语法以进行迭代,以便对于第二个数据帧中的每个空行,根据第一个数据帧中时间 (t) 的相应返回值,一个一个地填充空单元格,并且使用我上面描述的基本公式,第二个数据帧中前一个时间段 (t-1) 的价格。

我的想法是这样的

pri[2,] = pri[1,] * (1 + ret[2,])

但对于连续第二个数据帧中的所有剩余行(行 2:30,按列分隔)。任何建议将不胜感激。

【问题讨论】:

  • r 有实际的arrays。这些听起来像data.frames。如果您使用正确的术语或表明您确实在使用数组,那么帮助 wld 会更容易。区别很重要。

标签: r for-loop iteration


【解决方案1】:

下面解释了使用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

【讨论】:

    猜你喜欢
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    • 2012-10-27
    • 2021-12-20
    • 2018-12-05
    • 2010-09-11
    • 1970-01-01
    • 2020-07-30
    相关资源
    最近更新 更多