Reputation: 493
I'm trying to create a user defined function in R with an optional argument to save the plot as a pdf. I have the required parameter to default to FALSE. If TRUE, then save to pdf with filename.pdf. Have I gotten some syntax wrong:
seeplot <-function (save=FALSE) {
x <- seq(1,10,1)
y <- x^2
plot (x,y,type="l")
if (save==TRUE) pdf(file="save")
}
Thanks.
Upvotes: 1
Views: 424
Reputation: 109874
I think it's from not reading ?pdf
carefully that you're experiencing troubles. I'd let you struggle a bit (as struggle is good, shoot I often battle R) but I think maybe the logical save approach is not the best so I'll chime in. Here's 3 mistakes I see:
dev.off
Here is your function fixed:
seeplot <-function (save=FALSE) {
x <- seq(1,10,1)
y <- x^2
plot (x,y,type="l")
if (save) {
pdf(file="save.pdf")
plot (x,y,type="l")
dev.off()
}
}
But may I recommend supplying a file name instead of a logical save. This allows the user to name the file as they please:
seeplot <-function (file=NULL) {
x <- seq(1,10,1)
y <- x^2
plot (x,y,type="l")
if (!is.null(file)) {
pdf(file=file)
plot (x,y,type="l")
dev.off()
}
}
Upvotes: 9