繁体   English   中英

如何将 R 中的 while 循环生成的单列数据保存到数据帧?

[英]How do I save a single column of data produced from a while loop in R to a dataframe?

我在 R 中编写了以下非常简单的 while 循环。

i=1
while (i <= 5) {
  print(10*i)
  i = i+1
}

我想将结果保存到将是单列数据的数据框。 如何才能做到这一点?

你可以试试(如果你想要while

df1 <- c()
i=1
while (i <= 5) {
  print(10*i)
  df1 <- c(df1, 10*i)
  i = i+1
}
as.data.frame(df1)

  df1
1  10
2  20
3  30
4  40
5  50

或者

df1 <- data.frame()
i=1
while (i <= 5) {
  df1[i,1] <- 10 * i
  i = i+1
}
df1

如果您已经有一个数据框(我们称之为dat ),您可以在数据框中创建一个新的空列,然后通过其行号将每个值分配给该列:

# Make a data frame with column `x`
n <- 5
dat <- data.frame(x = 1:n)

# Fill the column `y` with the "missing value" `NA`
dat$y <- NA

# Run your loop, assigning values back to `y`
i <- 1
while (i <= 5) {
  result <- 10*i
  print(result)
  dat$y[i] <- result
  i <- i+1
}

当然,在 R 中我们很少需要像他那样编写循环。 通常,我们使用向量化操作来更快、更简洁地执行这样的任务:

n <- 5
dat <- data.frame(x = 1:n)

# Same result as your loop
dat$y <- 10 * (1:n)

还要注意的是,如果你确实需要一个循环,而不是一个矢量化操作,即特定的while循环也可以表示为一个for循环。

我建议参考 R 中数据操作的介绍书或其他指南。 数据框非常强大,它们的使用是 R 编程的必要和必不可少的部分。

如何使用 $?

[英]How do I paste a column from a R dataframe in a loop for a formula using the $?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM