我在 R 中撰寫了以下非常簡單的 while 回圈。
i=1
while (i <= 5) {
print(10*i)
i = i 1
}
我想將結果保存到將是單列資料的資料框。如何才能做到這一點?
uj5u.com熱心網友回復:
你可以試試(如果你愿意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
uj5u.com熱心網友回復:
如果您已經有一個資料框(讓我們稱之為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 編程的必要和必不可少的部分。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/348976.html
上一篇:如何獲得exec()的輸出?
