我想在 r 中使用 for 回圈生成大小為 10 的人口,如下所示(我知道應該有更簡單的方法來做到這一點而不使用回圈,例如
nPop <- 10
agent.list.2<- data.frame(id = 1:nPop,
state = 'S', #susceptible
mixing = runif(nPop,0,1))
但我只是想知道我是否仍然可以生成相同的人口for loop。)
nPop <- 10
for (i in 1:nPop){
agent <- data.frame(id = i,
state = 'S',#susceptible
mixing = runif(1,0,1))
}
agent
當我運行代碼時,我只得到了第 10 個代理。有什么辦法可以這樣做for loops嗎?
uj5u.com熱心網友回復:
如果您的偏好是停留在基本 R 的范圍內,并且如果您更喜歡 for 回圈,您也可以選擇:
nPop <- 10
agent <- data.frame(matrix(ncol = 3, nrow = nPop))
colnames(agent) <-c("id", "state", "mixing")
for (i in 1:nPop){
agent[i,] <- c(i, 'S', runif(1,0,1))
}
agent
uj5u.com熱心網友回復:
使用map從purrr包中進行迭代:
library(tidyverse)
nPop <- 10
agent <- map_dfr(seq_len(nPop), .f = function(i) {
data.frame(id = i,
state = 'S',#susceptible
mixing = runif(1,0,1))
})
結果:
> agent
id state mixing
1 1 S 0.5492558
2 2 S 0.9568374
3 3 S 0.9218307
4 4 S 0.2628695
5 5 S 0.6476246
6 6 S 0.9417889
7 7 S 0.2746807
8 8 S 0.1136945
9 9 S 0.2457556
10 10 S 0.9292233
如果你想使用 for 回圈,你可以這樣做:
library(dplyr)
agent <- data.frame()
nPop <- 10
for(i in seq_len(nPop)) {
df <- data.frame(id = i,
state = 'S',#susceptible
mixing = runif(1,0,1))
agent <- bind_rows(agent, df)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/445054.html
下一篇:從值串列中查找所有區域極值
