我正在通过R接口访问基于NetLogo代理的模型。我对此模型进行了多次迭代,这些迭代被存储在列表(res
)中。我可以使用代码res1<-res[[1]][,1]
访问单独的迭代,然后使用以下命令将每个结果列表转换为数据框:
mydata1 <-
data.frame(cbind(
unlist(res1$`map [x -> [sex] of x ] sort turtles`),
unlist(res1$`map [x -> [g] of x ] sort turtles`),
unlist(res1$`map [x -> [ticks] of x ] sort turtles`),
unlist(res1$`map [x -> [who] of x ] sort turtles`)
))
但是手动执行这些操作非常笨拙,我希望能够将列表拆分n次迭代,然后将结果列表转换为突出显示数据来自哪个迭代的数据框。
不幸的是,由于此数据来自我的模型,因此我不知道如何在此处显示示例数据,但希望您能看到我的问题。如果有任何不清楚的地方,乐意在评论中进一步扩展。
谢谢
P.S。这是显示清单创建方式的更多代码:
#' the function for the model
simfun <- function(carryingCapacity) {
NLCommand("set carryingCapacity ", carryingCapacity, "setup")
#' the reporters for the model
vars <- c("ticks", "who", "g" , "sex", "gm_val")
agents <- "turtles"
reporters <- sprintf("map [x -> [%s] of x ] sort %s", vars, agents)
nlogo_ret <- RNetLogo::NLReport(reporters)
run <-
NLDoReport(
10,
"repeat 520 [go]",
c("ticks", reporters),
as.data.frame = T,
df.col.names = c("ticks", reporters)
)
}
#' Replicate the simulation
rep.sim <- function(carryingCapacity, rep) {
lapply(carryingCapacity, function(x) replicate(rep, simfun(x)))
}
#' run the model
K <- c(300) #' carrying capacity
res <- rep.sim(K, 2) #' replicate sim 5 times for each K
#' pull out the data for each run from the list columns
res1<-res[[1]][,1]
res2<-res[[1]][,2]
#' transform each run into a dataframe
mydata1 <-
data.frame(cbind(
unlist(res1$`map [x -> [sex] of x ] sort turtles`),
unlist(res1$`map [x -> [g] of x ] sort turtles`),
unlist(res1$`map [x -> [ticks] of x ] sort turtles`),
unlist(res1$`map [x -> [who] of x ] sort turtles`)
))
mydata2 <-
data.frame(cbind(
unlist(res2$`map [x -> [sex] of x ] sort turtles`),
unlist(res2$`map [x -> [g] of x ] sort turtles`),
unlist(res2$`map [x -> [ticks] of x ] sort turtles`),
unlist(res2$`map [x -> [who] of x ] sort turtles`)
))