编辑:
我想以最简单的形式知道的事情:
如何通过for循环获取以下累积数据集:
1 = 1
1+2 = 3
1+2+3 = 6
1+2+3+4= 10
1+2+3+4+5 = 15
当我尝试此代码时;我没有得到想要的结果
test <- c(0,0,0,0,0)
for (i in 1:5) {test[i] <- sum(i)}
test
[1] 1 2 3 4 5
实际问题:
我想将以下公式转换为R:
以下是我尝试过的方法,但不幸的是,它给了我错误的值:
P <- rnorm(20,100,6)
exp <- function( theta){
for (t in (3:20)){
for (k in (1:(t-1))){
X[t] = (1-theta) * sum( theta^(k-1)*(P[t-k] - P[t-k-1])) + theta^(t-1)}
}
我确定我错误地使用了sum运算符,但是我的大脑完全被阻塞了,我不知道如何在这里正确使用它。
感谢您的帮助。
答案 0 :(得分:0)
令人费解的方式:
for(i in 1:5){
if(!exists("x")){
print(x <- 1)
} else {
print(x <- x + i)
}
}; rm(i, x)
简单方法:
cumsum(1:5)
答案 1 :(得分:0)
您可以创建函数exp
,以使其依赖于theta
和t
,然后取决于Vectorize
。试试:
set.seed(1)
P <- rnorm(20,100,6)
exp <- function(theta, t){
for (k in 1:(t-1)) {
X = (1-theta) * sum(theta^(k-1)*(P[t-k] - P[t-k-1])) + theta^(t-1)
}
return(X)
}
exp <- Vectorize(exp)
exp(0.6, 3:20) # setting theta to 0.6 for instance
# output
[1] 3.600000e-01 2.160000e-01 1.296000e-01
[4] 7.776000e-02 4.665600e-02 2.799360e-02
[7] 1.679616e-02 1.007770e-02 6.046618e-03
[10] 3.627971e-03 2.176782e-03 1.306069e-03
[13] 7.836416e-04 4.701850e-04 2.821110e-04
[16] 1.692666e-04 1.015600e-04 6.093597e-05
您还可以将for
循环用于不同的theta值:
my.list <- list()
for (i in seq(0.1, 0.9, 0.1)) {
val = exp(i, 3:20)
my.list[[paste0("theta", i)]] <- val
}
str(my.list)
# my.list
List of 9
$ theta0.1: num [1:18] 1e-02 1e-03 1e-04 1e-05 1e-06 ...
$ theta0.2: num [1:18] 4.0e-02 8.0e-03 1.6e-03 3.2e-04 6.4e-05 ...
$ theta0.3: num [1:18] 0.09 0.027 0.0081 0.00243 0.000729 ...
$ theta0.4: num [1:18] 0.16 0.064 0.0256 0.0102 0.0041 ...
$ theta0.5: num [1:18] 0.25 0.125 0.0625 0.0312 0.0156 ...
$ theta0.6: num [1:18] 0.36 0.216 0.1296 0.0778 0.0467 ...
$ theta0.7: num [1:18] 0.49 0.343 0.24 0.168 0.118 ...
$ theta0.8: num [1:18] 0.64 0.512 0.41 0.328 0.262 ...
$ theta0.9: num [1:18] 0.81 0.729 0.656 0.59 0.531 ...