write function help in R

孤人 提交于 2019-12-25 02:32:38

问题


> MLest<- arima(X, order = c(1,0,0), method = c("ML"))
> MLest

Call:
arima(x = X, order = c(1, 0, 0), method = c("ML"))

>Coefficients:
         ar1  intercept  
      0.2657    -0.0824  
  0.0680     0.1018  
sigma^2 estimated as 1.121:  log likelihood = -295.23,  aic = 596.47

I would like to write the 0.2657 and 1.121 results to an output file. I have defined a path and file name and here is my codes.

When I use, write(MLest, file=filename, append=TRUE, sep="\t") I got the following error:

Error in cat(list(...), file, sep, fill, labels, append) : 
  argument 1 (type 'list') cannot be handled by 'cat'

When I use, write.table(MLest[1:2], file=filename,sep=" ", col.names = F, row.names = F)

It works but I have:

 0.265705946688229 1.12087092992291  
-0.0823543583874666 1.12087092992291

I would like to have a result as: 0.265705946688229 -0.0823543583874666 1.12087092992291 (each value to different columns)

What should I use?


回答1:


write.table is a bit of an overkill for writing a single line in a file. I'd recommend you use cat directly on a vector. As you can see from the error message, that's what write.table uses under the hood. This works:

cat(with(MLest, c(coef, sigma2)), "\n", sep = "\t",
    file = filename, append = TRUE)

But I will point out: every time you run this command, a file handle is created, moved to the end of the file, a new line is written, then the filehandle is closed. It is quite inefficient and you'd better open a file connection instead:

fh <- open(filename)
for (...) { 
   MLest <- arima(...)
   cat(with(MLest, c(coef, sigma2)), "\n", sep = "\t", file = fh)
}
close(fh)

This way, only one filehandle is created and it always points to the end of your file.


Alternatively, you could wait to have all your arima outputs to create a whole data.frame or matrix of coefficients and only then print it with a single call to write.table.

Assuming you have built a list ll of arima outputs, you can create and write that matrix of coefficients by doing:

output.mat <- t(sapply(ll, with, c(coef, sigma2 = sigma2)))
write.table(output.mat, file = "test.csv", row.names = FALSE)



回答2:


Try

write.table(unique(as.vector(MLest[1:2])), file=filename,sep=" ", col.names = F, row.names = F)


来源:https://stackoverflow.com/questions/20299964/write-function-help-in-r

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!