R中的FOR循环;没有得到我想要的东西

时间:2014-03-12 04:06:24

标签: r for-loop

只是一个普遍的问题:

当我跑步时:

ok<-NULL
for (i in 1:3) {
ok[i]=i^2
i=i+1
}

循环有效(如预期的那样)。

> ok
[1]  1  4  9

现在当我尝试做类似的事情时:

ok<-NULL
for (i in 1:3) {
ok[i]=i^2
x[i]<-ok[i]+1
y[i]<-cbind(ok[i],x)
i=i+1
}

我想要:

y = 1
    2
    4
    5
    9
    10

相反,我得到:

Warning messages:
1: In y[i] <- rbind(ok[i], x) :
  number of items to replace is not a multiple of replacement length
2: In y[i] <- rbind(ok[i], x) :
  number of items to replace is not a multiple of replacement length
3: In y[i] <- rbind(ok[i], x) :
  number of items to replace is not a multiple of replacement length
4: In y[i] <- rbind(ok[i], x) :
  number of items to replace is not a multiple of replacement length
5: In y[i] <- rbind(ok[i], x) :
  number of items to replace is not a multiple of replacement length

提前致谢。

3 个答案:

答案 0 :(得分:1)

使用此命令y[i]<-cbind(ok[i],x),您尝试使用多个元素替换向量中的一个元素。这会导致错误。

答案 1 :(得分:1)

如果你想得到1:3平方,你可以使用:

ok <- (1:3)^2
ok
# [1] 1 4 9

如果您希望得到1:3平方以及它们之后的数字,您可以尝试:

as.vector(rbind(ok, ok+1))
[1]  1  2  4  5  9 10
R中的

for循环通常是解决问题的错误方法。

答案 2 :(得分:1)

在开始编程之前,你应该阅读R基础知识。

  • 你不必在循环中增加i(实际上它非常令人困惑)。
  • 你没有cbind或rbind向量,这是针对data.frame列和行的。
y <- NULL
for(i in 1:3){ ok <- i^2; x <- ok + 1; y <- c(y, ok, x) }

or:
as.vector(sapply(1:3, function(i){ ok <- i^2; x <- ok + 1; c(ok, x) }))