0

I think my mistake here is a misunderstanding about how functions operate within R but I do have some concerns that this might give me some strange results.

If I declare a parameter outside of a function, it overrides any parameters declared within the function call.

x<- 6

example<- function(...){
print(x^2)
}

example()

returns 36. I am ok with this.

However, if I run the function again and declare the variable, it gets ignored.

example(x =5)

still returns 36.

I can understand what is happening, but I don't really get why. Is using the ... bad practice in this case?

if my function is

example<- function(x){
print(x^2)
}

it works.

Jamzy
  • 159
  • 1
  • 7
  • Related, possible duplicate https://stackoverflow.com/q/5890576/680068 In other words read the manuals: `?dots` – zx8754 Jul 02 '20 at 06:58
  • You can try: `example1 <- function(...){print(list(...)[["x"]]^2)}` or `example2 <- function(...){list2env(list(...), environment()); print(x^2)}` – GKi Jul 02 '20 at 07:07
  • Thank you - I see those answers and the answer below. I don't think it is a duplicate as I am looking to see what is happening, as well as seeking guidance for what is best practice. – Jamzy Jul 02 '20 at 07:34

1 Answers1

1

What you should ideally write is :

example<- function(...){
    x <- c(...)
    x^2
}

example(5)
#[1] 25

example(5, 6)
#[1] 25 36

example() would return an empty value since you have not passed anything. Don't rely on global variables to be evaluated in the function. You should pass the variables in the function explicitly.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213