为什么我的for循环在每次迭代中使用rbind后只返回1行?

问题描述 投票:0回答:1

我试图获得以下等式的一组解:y = x ^ 2 - t [i],对于参数t在[2,3]中变化的所有值。

我试图实现一个for循环,在每次迭代中计算计算并将结果rbinder到一个数据帧,以便以后使用。

t<-seq(from = 2, to = 3, by = 0.005)
x<-seq(from = 0, to = 30, by = 0.05)

d<-data.frame()
for (i in length(t)) {
  y<- x^2 - t[i]
  d<-rbind(d,y)
  }

d

我希望for循环的输出是201行和601列的数据帧,但实际输出只有一行601列。

r
1个回答
2
投票

如果更改for循环以迭代1:length(t),它将创建201行。

t <- seq(from = 2, to = 3, by = 0.005)
x <- seq(from = 0, to = 30, by = 0.05)

d <- data.frame()

for (i in 1:length(t)) {
  y <- x^2 - t[i]
  d <- rbind(d,y)
}

str(d)
© www.soinside.com 2019 - 2024. All rights reserved.