Home > Enterprise >  How to use list(...) in loop of function
How to use list(...) in loop of function

Time:06-05

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" 

CodePudding user response:

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"
  •  Tags:  
  • r
  • Related