How do you invert the functional parameters for lapply in R?

I've been wondering for a while: in R, what is the recommended way to invert function parameters for order-dependent functions to allow list-style processing?

For a simple example, let's say I have a list of numbers and one divisor.

numerator = list(5, 10, 15, 250)
denominator = 2

      

I want to divide each number by a divisor. I know that I can easily use a numeric vector in this case:

as.numeric(numerator)/denominator
# [1]   2.5   5.0   7.5 125.0

      

But in the real world, a list can contain a more complex data structure, which makes vector wrapping impossible. This is a simple example. Instead, we could use lapply (or sapply) like this to give the same answer:

sapply(numerator, "/", denominator)
# [1]   2.5   5.0   7.5 125.0

      

So here's the question: what do you do if you want to flip the arguments to a function? As is the case, divide the "denominator" by each number, and not vice versa? Usually "/" you provide the numerator, then the denominator. But now I want to split the denominator by the numerator, the "/" function can no longer be used with sapply (for which the list item must be the first function argument).

I want this result:

denominator/as.numeric(numerator)
# [1] 0.4000000 0.2000000 0.1333333 0.0080000

      

I usually do this to write a new function that inverts the parameters:

inverse_divide = function(denominator, numerator) {
    return(numerator/denominator)
}

      

Now it works:

sapply(numerator, inverse_divide, denominator)
# [1] 0.4000000 0.2000000 0.1333333 0.0080000

      

But this is getting old. Is there an easier way?

+3


source to share


2 answers


You can use mapply

. He can take the appropriate elements from both vector

and list

, and divide /

. In this case, there is only one element for the "denominator", so it will be reworked. If the length of the elements is the same in both the "numerator" and "denominator", the corresponding elements are used as above.



 mapply(`/`, denominator, numerator)
 #[1] 0.4000000 0.2000000 0.1333333 0.0080000

 mapply(`/`, numerator, denominator)
#[1]   2.5   5.0   7.5 125.0

      

+3


source


Another way:



sapply(numerator, function(x) denominator / x)
## [1] 0.4000000 0.2000000 0.1333333 0.0080000

      

+3


source







All Articles