我在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中编程的必要和重要部分