*apply with three-argument functions in R

Asked

Viewed 389 times

8

I created a function of three arguments and I want to apply it to a Matrix 200 X 3 where in 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?

2 answers

4

If you have a list, and want to call a function using the elements of this 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))

Put that together, you can get to 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: the apply apply the function to each row of the array, which in turn is an array 3x1; convert that array arr in a list, and I use that list as arguments to minhafuncao.

Example in the ideone. Note: I’m beginner in R, I don’t know if this is the best way, but at least it works as expected.

  • Thank you very much, although being more complicated works. It was a great help.

3

You can do it directly with apply by separating the three arguments from 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 element of the line as the first argument of the function, the second element of the line as the second argument, and the third element of the line as the third argument.

  • 1

    Thank you so much! That’s exactly what it was

  • For nothing @user11849! If you think the answer has met your need, you can accept it! Hugs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.