R问题返回函数使用循环的输出
问题描述:
我有一个问题,当我在循环中使用它时,会返回R中创建的函数的输出。我正在尝试将多个MCMC模型的输出结合到一个R对象中。R问题返回函数使用循环的输出
功能:
get_scrUN_output <- function(filename){
out <- filename
nam<-c("sigma","lam0","psi", "N")
nam<-match(nam,dimnames(out[[1]]$sims)[[2]])
out.lst<-mcmc.list(
as.mcmc(out[[1]]$sims[200001:300000,nam]),
as.mcmc(out[[2]]$sims[200001:300000,nam]),
as.mcmc(out[[3]]$sims[200001:300000,nam]))
s <- summary(out.lst)
gd <- gelman.diag(out.lst,multivariate = FALSE)
output_table <- rbind(as.data.frame(t(s$statistics)),
as.data.frame(t(s$quantiles)),
as.data.frame(t(gd$psrf)))
return(output_table) }
我用来创建RDATA MCMC输出的列表通过函数来运行的代码:当我使用功能上的单个输出文件
scrUN.ET <- list.files(getwd(),"out.*ET.RData")
scrUN.lst <- as.vector(substring(scrUN.ET,1))
scrUN.lst <- str_sub(scrUN.lst, 1, str_length(scrUN.lst)-3)
>scrUN.lst
[1] "BBout11FL" "BBout11TL" "BBout12TL" "BBout13FL" "BBout13TL"
,它的工作原理:
get_scrUN_output(BBout11FL)
sigma lam0 psi N
Mean 130.43594323 14.5319368 0.3361405211 335.8042733
SD 7.28386725 9.7311139 0.2743725813 274.6828277
Naive SE 0.01329846 0.0177665 0.0005009335 0.5014999
Time-series SE 1.28032869 1.3886577 0.0360607870 36.5692414
2.5% 118.37718370 0.6129902 0.0300165600 30.0000000
25% 124.29743884 5.7535456 0.0958156210 95.0000000
50% 130.40628214 15.1264454 0.2426328827 242.0000000
75% 135.99836262 19.9685209 0.5403864215 541.0000000
97.5% 145.11615201 34.9438198 0.9298185748 930.0000000
Point est. 1.59559993 4.4590599 1.0677998255 1.0678381
Upper C.I. 2.56854388 9.5792520 1.2186078069 1.2186933
但是,当我尝试运行所有输出文件通过函数使用循环我得到一个NULL输出。
scrUN.output <- rbind(
for (i in seq_along(scrUN.lst)){
get_scrUN_output(get(scrUN.lst[i]))
}
)
>scrUN.output
NULL
谢谢!
答
我认为这是你要求的。这是最终代码部分的编辑。因为没有任何东西被for循环返回,所以你在使用rbind。
scrUN.output <- lapply(scrUN.lst, function(i) get_scrUN_output(get(i)))
scrUN.output <- do.call(rbind, scrUN.output)
scrUN.output
答
原因是你rbind
-什么也没有。
下面是一个简化的例子,演示了你的代码正在做什么 - for循环没有给变量分配任何东西,这就是为什么你最终得到NULL
。
xx <- rbind(
for(i in c(1,2)){
i
}
)
print(xx) # NULL
试试这个:
scrUN.output <- list() # initialize a list
for (i in seq_along(scrUN.lst)){
# update the list contents
scrUN.output[[i]] <- get_scrUN_output(get(scrUN.lst[i]))
}
# finally, rbind eveything
scrUN.output <- do.call(rbind, scrUN.output)
或者更好的,使用lapply
:
scrUN.output <- lapply(scrUN.lst, get_scrUN_output)
scrUN.output <- do.call(rbind, scrUN.output)
完美的作品!谢谢。 – JoB