I'm struggling with using mapply on functions I construct where I have one or more arguments that are needed because I am programming in a bigger environment, for example if I write a function where one of the arguments are data.
fun_test <- function(data,col,val1,val2){return(data[col][1,] * val1-val2)}
So data and col can for example be constant, but I want to vary the output of my function depending on val1 and val2:
> mapply(FUN=fun_test,mtcars,"cyl",mtcars$cyl,mtcars$cyl*2)
Error in data[col][1, ] : incorrect number of dimensions
I'm trying to understand how mapply works; I surely cannot pass mtcars, and "cyl" as a vector, can I?
EDIT: I have an environment in which the data may vary, e.g. sometimes I use mtcars, sometimes it is another dataset. So I cannot hardcode the data into the function
EDIT2: 1) I have data some dataset, 2) I have different Excel-files that I read into R, 3) I make a lookup function that extracts information from these Excel-files in R, 4) for one or two variables (from the dataset) at the time I go into the lookup-functions I created and extract information.
So these lookup functions depend on both the data (the variables I need to lookup) and the Excel-files that I use to do the looking up.
mapply is a multidimensional lapply. This means that instead of iterating over just one object (i.e. the columns of a data.frame or the elements of a vector), it iterates over multiple ones at the same time. The only condition is that the length of those objects needs to be the same, i.e. the columns of a data.frame and the lengths of the vectors. So, you cannot pass constants (unless you pass in a vector of the same constants to match the length, but why would you do that).
Try an easy example (sums the same indexes of the vectors):
mapply(sum, 1:10, 11:20)
So, in your case, just pass in the constants straight into the function:
fun_test <- function(val1, val2){return(mtcars['cyl'] * val1 - val2)}
mapply(FUN=fun_test, mtcars$cyl, mtcars$cyl*2)
Update:
Then I think what you need is to include mapply within your function. In that way you can add any argument you like (both constants and variable). It would look like this:
myfunc <- function(data, col, val1, val2) {
fun_test <- function(val1, val2) {
data[col] * val1 - val2
}
mapply(FUN=fun_test, val1, val2)
}
myfunc(mtcars, 'cyl', mtcars$cyl, mtcars$cyl*2)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With