* apply with three-argument functions in R

6

I've created a three-argument function and I want to apply it to a 200 X 3 matrix where on each line are the three arguments I need to use in the function. As a result I would get a vector of size 200. How can I do this?

    
asked by anonymous 27.06.2014 / 07:44

2 answers

3

If you have a list, and want to call a function using the elements of that list as parameters, you can use do.call :

minhafuncao <- function(a, b, c) {
    return(a * b + c)
}

minhafuncao(1, 2 3)
do.call("minhafuncao", list(1, 2, 3))

To convert an array to a list, you can use lapply with the identity function:

x <- array(1:3, dim=c(3,1))

do.call("minhafuncao", lapply(x, identity))

Putting this together, you can get what you're looking for:

x <- array(1:15, dim=c(5,3))

apply(x, 1, function(arr) do.call("minhafuncao", lapply(arr, identity)))

Explaining: apply applies the function to each row of the array, which in turn is an array 3x1 ; I convert this array arr to a list, and I use this list as arguments to minhafuncao .

Example in ideone. Note: I'm a beginner in R, I do not know if this is the best way, but at least it works as expected .

    
27.06.2014 / 12:23
2

You can do directly with apply, separating the three arguments of the line as the parameters.

Resultado <- apply(matrix, 1, function(linha) suafuncao(linha[1],linha[2],linha[3]))

In this case you are using the first line element as the first argument of the function, the second line element as the second argument, and the third line element as the third argument.

    
29.06.2014 / 03:30