【发布时间】:2020-10-30 11:55:24
【问题描述】:
我创建了一个循环来计算以下公式: values = 1+PE - (1+(i^w))^(1/w)) 其中 PE 和 w 变化如下:
#creation of my variables
w <- seq(1, 4, by = 0.1)
PE <- seq(1, 2, by = 0.1)
#creation of a matrix where I will be storing the results of the loop
results <- matrix(nrow= length(PE) , ncol= length(w))
#loop where w and PE are changing
for(i in PE){
for (j in w){
results <- (1+i - (1+(i^j))^(1/j))
print (results)
}
}
results
如果我运行它,我会获得一个列表,其中打印了我的所有值,但我面临 2 个问题:
i) 我无法存储这些值。当我在循环外打印结果时,我得到 1 个值而不是全部。所以我不能操纵它们来创建一个矩阵,也不能创建一个数据框。
ii) 我最初为要存储的这些值创建了一个矩阵,因此当我在循环中添加时: results[i, j] 我得到了几个具有许多 NA 值的矩阵,而我应该只得到一个矩阵。这个矩阵应该有11行31列
【问题讨论】:
-
result <- sapply(w, function(j) (1+PE - (1+(PE^j))^(1/j)))使用向量运算!
标签: r loops matrix nested-loops