1

我正在尝试将 JAGS 中的一些采样输出值导出为 .csv 格式,以便在 R 中执行进一步分析,但遇到了一些麻烦。

> 
> codaSamples
[[1]]
Markov Chain Monte Carlo (MCMC) output:
Start = 4001 
End = 14000 
Thinning interval = 1 
           pai     theta[1]     theta[2]   theta[3]   theta[4]
[1,] 0.9774972 0.0081192689 0.0101738296 0.06981109 0.10674466
[2,] 0.9527935 0.0076402088 0.0099482287 0.07593964 0.11060883
[3,] 0.9467507 0.0076402088 0.0099482287 0.07593964 0.11060883
[4,] 0.9514251 0.0076402088 0.0099482287 0.07593964 0.11060883
[5,] 0.9419245 0.0076402088 0.0099482287 0.07593964 0.11060883
[6,] 0.9914296 0.0076402088 0.0099482287 0.07593964 0.11060883
[7,] 0.9903451 0.0076402088 0.0099482287 0.07593964 0.11060883
[8,] 0.9917113 0.0064704730 0.0095551321 0.06748512 0.11033123
...
... 

[10000,] 0.9917113 0.0064704730 0.0095551321 0.06748512 0.11033123

> write.csv(codaSamples,"CODASAMPLES.csv",row.names=FALSE)
Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors =       stringsAsFactors) : 
cannot coerce class '"mcmc.list"' into a data.frame
4

2 回答 2

3

amcmc.list可以包含多个链,您需要在写入 CSV 文件时选择所需的链:

write.csv(codaSamples[[1]], "CODASAMPLES.csv",row.names=FALSE)

应该做“正确的事情”,尽管我目前没有链来测试它。

于 2013-11-07T17:50:13.510 回答
2

write.table expects a data frame or a matrix (if you don't pass it one, it will try and coerce it). If you look at the structure of codaSamples with e.g. str(codaSamples) you'll see that it is a list object with elements which are lists or data frames or matrices (I don't know what it actually is). IF it is mixed like that, write.table has no idea how to turn it into a csv.

If you want to select only the matrix you can find the name of the element with names(codaSamples) or again from str(codaSamples) and then do something like sample.mcmc <- codaSamples[['Matrix']] or whatever the name is, then you should be able to save sample.mcmc to a file just like you have.

于 2013-11-07T17:51:37.283 回答