Search code examples
rjags

How to write some R data into a .csv file?


I'm trying to export some sampled output values from JAGS into .csv format in order to perform further analysis in R, but got some troubles.

> 
> 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

Solution

  • a mcmc.list can contain multiple chains, you'd want to select out the chain you want when writing to the CSV file:

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

    Should do the "right thing", although I don't have a chain to test this with at the moment.