2

Please help me understand how the ... arguments works in a function. I am trying to input values into my function such as the following:

test_data<-function(data, ...){
  pr <- list(...)
  nm <- names(data)
  for(i in seq_along(nm)){
    if(pr == nm[i]) nm<-(nm[-i])
  }
  return(nm)
}

This should pass any value to the dots and check if the name matches it, if it does then remove the name from the names of the data. However, when I do this I get the following:

test_data(mtcars, 'carb')
>NULL

I should get:

[1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec"
 [8] "vs"   "am"   "gear" 
1
  • 1
    I made a silly mistake, for test_data(mtcars, 'carb'), I had instead test_data(data, 'carb'), and so it returned NULL. It does work but the answer is definitely much cleaner! Commented Jun 4, 2022 at 12:58

1 Answer 1

2

There is no need for a for loop. You could do:

Note: Instead of wrapping the args passed via ... in a list I put them in a vector.

test_data <- function(data, ...) {
  pr <- c(...)
  nm <- names(data)
  nm[!nm %in% pr]
}

test_data(mtcars, "carb")
#>  [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear"

# Example with multiple args
test_data(mtcars, "carb", "am", "foo", "bar")
#> [1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "gear"
Sign up to request clarification or add additional context in comments.

Comments

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.