3

I have the following data:

x <- 11
w <- "12AAB"
y <- "var1"

I also have a function funky(x,w,y){}

With the above 3 constants as inputs I can apply the following:

funky(x = x, w = w, y = y)

Which imports a bunch of data and performs some calculations and saves the file in a specific folder. I now however want to expand the function over to different "vars" where y is a character vector. For instance;

x <- 11
w <- "12AAB"
y <- c("var1", "va2", "var3")

How can I use lapply to run the function using x = 11, w = 12AAB and firstly run using y = var1, then secondly y = var2 etc.

I do not have anything specific to apply the function to so I cannot use lapply(data, funky)

krads
  • 1,350
  • 8
  • 14
user113156
  • 6,761
  • 5
  • 35
  • 81

1 Answers1

3

You can iterate over y with lapply, hard-coding x and w.

lapply(y, funky, x = x, w = w)

This will run funky the length n of y times, with

funky(x = x, w = w, y = y[1])
funky(x = x, w = w, y = y[...])
funky(x = x, w = w, y = y[n])
Rich Scriven
  • 97,041
  • 11
  • 181
  • 245
  • Excellent answer!+1 Just to add to that, note the warning and best practice from `?lapply` to avoid being caught out: > "Arguments in ... cannot have the same name as any of the other arguments, and care may be needed to avoid partial matching to FUN. In general-purpose code it is good practice to name the first two arguments X and FUN if ... is passed through: this both avoids partial matching to FUN and ensures that a sensible error message is given if arguments named X or FUN are passed through ..." So suggestion would be to name X and FUN like: `lapply(X=y, FUN=funky, x = x, w = w)` – krads Oct 13 '18 at 23:38