1

I am a beginner in R. For example i have a function called w whose code is listed below:

    w<-function(x){
       a<-x+2
       plot(a)
      }

How can i add these arguments in the function so that

  1. Export: a number equal to 0 if result should be allowed on screen and to 1 if the result should be printed in a text file.

  2. Tfile: name of the text file where the results will be written to;

  3. Gfile:name of the pdf file where the graph will be written to.

1
  • function(x,export,tfile,gfile) ? Commented May 7, 2015 at 14:09

2 Answers 2

4

To include further arguments in a function, simply list them in function().

w <- function(x, export, tfile, gfile) {
    a <- x + 2
    if (export == 1) {
        write.csv(a, file = tfile)
    } else if (export == 0) {
        pdf(file = gfile)
        plot(a)
        dev.off()
    }
}

For more information on writing and debugging functions in R, see this article.

Sign up to request clarification or add additional context in comments.

Comments

-1

As the others have pointed out, just separate additional arguments with commas. You can have as many as you want.

w <- function(x, export, tfile, gfile)

Assigning values within the function definition allows them to have default arguments, so you can choose not to include them

w <- function(x, export = 0, tfile = "w.csv", gfile = "w.pdf")

I will add that a handy thing for plot functions (and many other functions) is the ellipsis ... construct, which basically means "any other relevant arguments". For instance, doing something like this allows you to optionally pass further graphical parameters to your plot (e.g. label names, title).

w <- function(x, ...){
    a <- x + 2
    plot(a, ...)
}
w(10, main="Main title")
w(15, type='l', col='red')

4 Comments

The OP specified that export takes values 1 and 0 rather than TRUE and FALSE. Also, your last example won't run since you haven't enclosed both the definition of a and the call to plot() in brackets; a will be undefined when you try to plot it.
My mistake! Both have been fixed. Although to be fair, the way R evaluates logical statements (like the one in your post), FALSE and 0 are equivalent.
Yes, they do have the same effect, and indeed I would generally prefer to use a logical value in this context. (Btw, not the downvoter, though I probably would have posted this as a comment rather than an answer.)
I agree about the comment, but I don't have enough reputation yet to post comments on posts other than my own (need 50, but I have 49...).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.