[英]Using for-loop to fill vector in R
I'm simplifying this question, for clarity.为了清楚起见,我正在简化这个问题。
Say I want to create a vector with a number of elements with the value zero.假设我想创建一个包含多个值为零的元素的向量。 I then want to use a for-loop to replace every element with its own index number inside the vector.
然后,我想使用 for 循环将向量中的每个元素替换为其自己的索引号。
Can this be done?这可以做到吗?
K <- 11
p <- rep(0, K + 1)
for (k in 0:K) {
p[k+1] <- .... ?
}
Here's one solution if I understand your expected output:如果我了解您预期的 output,这是一种解决方案:
K <- 11
p <- rep(0, K + 1)
for (k in 0:K) {
p[k + 1] <- k
}
Which returns:哪个返回:
[1] 0 1 2 3 4 5 6 7 8 9 10 11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.