user3510503
user3510503

Reputation: 358

Passing multiple arguments to lapply from a dataframe

I'm trying to apply a function to all combinations of 2 arguments using "apply" function in R but I'm getting some errors.

Here's the breakdown of what I'm doing:

I have 2 lists of arguments as follows:

list1 <- c('a','b','c')
list2 <- c('x','y','z')

I need to pass all possible combinations of these two lists to a function, so I create a dataframe as follows:

combined<-expand.grid(list1 = list1, list2 = list2)

The combined dataframe now contains 9 rows of data with all possible combinations of these 2 lists.

Now,I have a function my_func() which accepts 2 arguments e.g. my_func('a','x') and generates some output.

I'd like to apply this function to all these 9 rows of the combined dataframe created above, so I use apply function as follows:

apply(x,resp_rate)

Running this code generates the following error.

Error in match.fun(FUN) : argument "FUN" is missing, with no default

I'd really appreciate if someone here could tell me what am I doing wrong.

Upvotes: 0

Views: 541

Answers (1)

Ronak Shah
Ronak Shah

Reputation: 388982

With apply in the second argument you need to pass the MARGIN which is to specify if you want to apply the function row-wise (1) or column-wise (2). Also you would need to use an anonymous function here since your function accepts two separate arguments.

apply(combined, 1, function(x) my_func(x[1], x[2]))

Upvotes: 1

Related Questions