0

I have several questions to do with handling some data in R:

  1. I am using this statement: detailsTable <- read.table(file=commandArgs()[6], header=TRUE, col.names=c("a", "b", "c", "d", "e")) and it seems that the table is not being loaded correctly... but if I specify the path of the file I am loading excplicitly then all goes well. What am I doing wrong?

  2. I plot the data contained in that table mentioned above. How do I save the plot (eg: plot.savePDF("plot.pdf")) to a PDF file?

  3. How could I redirect the output of, for example, cor(detailsTable$a, detailsTable$b) to a file? and how do I write a simple string to a file. eg: "Correlation of the data: " + cor(...)

  4. How do I plot the line of best fit on an existing plot?

All of this is in R.

Many thanks to anyone who can help,

ExtremeCoder

  • 1
    Please see [my previous answer to you](http://stackoverflow.com/questions/3506007/running-r-code-from-command-line-windows), in particular point 5. The *Introduction to R* has a step-by-step appendix that covers some of your questions. – Dirk Eddelbuettel Aug 17 '10 at 20:03
  • 1
    You should separate this into multiple questions, as these are unrelated problems. – Aniko Aug 17 '10 at 21:16
  • What is the output of commandArgs()[6]? – Roman Luštrik Aug 18 '10 at 07:54

3 Answers3

2

I plot the data contained in that table mentioned above. How do I save the plot (eg: plot.savePDF("plot.pdf")) to a PDF file?

 pdf("filename.pdf")
 plot(...)
 dev.off()

How could I redirect the output of, for example, cor(detailsTable$a, detailsTable$b) to a file? and how do I write a simple string to a file. eg: "Correlation of the data: " + cor(...)

check the write.table manual page (?write.table)

How do I plot the line of best fit on an existing plot?

x <- 1:10
y <- 2 * x + runif(10) 
plot (x, y, pch=20)
fit <- glm(y~x)
coefs <- coef(fit)
abline(coefs, lwd=2, col='red')
# Or also, without finding the coefficients
abline(fit, lwd=2, col='red')
nico
  • 50,859
  • 17
  • 87
  • 112
  • You might also want to check out the `cat` command for writing stuff to files. Also, `abline(fit)` will also do the trick (you don't need to grok out the coeffs). – Jonathan Chang Aug 18 '10 at 00:07
1

You can redirect output using sink().

dank
  • 841
  • 1
  • 8
  • 15
0

How to save the plot you're producing depends on which plotting system you're using. Assuming it's base graphics, you need to start a pdf graphics device, then plot to it.

pdf(file = "path/file.pdf", width = 5, height = 5)
...
#plotting commands here
...
dev.off()
JoFrhwld
  • 8,867
  • 4
  • 37
  • 32