【发布时间】:2015-05-01 19:14:53
【问题描述】:
我有一个数百行的 R 脚本,包括几个随机化函数。每次运行它都会得到不同的结果。
我正在考虑对我的模型进行敏感性分析,我有兴趣将我的脚本运行数百次并比较结果。
经过一番研究,我发现lapply 和knitr 的组合可能是一个可能的解决方案:
result <- c("B:/Documents/result.R")
resultsList <- lapply(1:100, function(n) knit(input=result, NULL))
不幸的是,这不起作用。谁能解释一下为什么?
非常感谢!
更新
脚本如下所示:
#Records
dataID = c(01, 03, 05)
localityNumber = c(2000, 4000, 5000)
records = data.frame(dataID, localityNumber)
#Locality number / Postcode conversion table
localityNumber = c(2000, 2000, 2000, 4000, 5000)
postCode = c(6766, 6767, 6768, 7041, 8046)
allocationTable = data.frame(localityNumber,postCode)
rm(dataID, localityNumber, postCode)
#Create random postcode id
count <- aggregate(allocationTable, by=list(allocationTable$localityNumber), FUN=length)
names(count) <- c("localityNumber", "count", "count.2")
allocationTable <- join(x=allocationTable, y=count)
#Test with for localityNumber with three postcodes
allocationThree <- allocationTable[which (allocationTable$count == "3"),]
testThree <- nrow(allocationThree) / 3
repThree <- rep(1:3, testThree)
allocationThree$id <- repThree
allocationThree$count <- allocationThree$count.2 <- NULL
rm(count, rep, testThree)
records$id <- repThree
#Randomly allocate
records <- join(records, allocationThree)
我想多次重复此脚本并将records data.frame 的值存储在一个列表中。
【问题讨论】:
-
lapply(1:100, function(n)source("B:/Documents/result.R"))不好? -
嗨,Khashaa,感谢您的意见。我尝试了
source方法:lapply(1:100, function(n) source(result)),但我得到了一个包含 100 次重复的 2 个参数(value和visible)的列表。我认为这是正确的方向,但我想得到一个包含脚本输出结果的列表,而不是简单地运行它。 -
你的脚本是什么样子的?
-
@Gion Mors 如果你能提供你的函数或名称的伪代码,或者关于你的函数等的简要信息,那就太好了
-
呃...棘手的问题!该脚本为一组记录随机分配邮政编码。输出是带有记录 ID 和分配的邮政编码的数据帧。由于脚本随机分配,每次我运行它时,邮政编码变量的值都会改变。希望我回答了你的问题!