Tom Martens
Tom Martens

Reputation: 776

anonymous function with multiple parameters

don't ask if my example is reasonable, maybe there are examples how to circumvent my question, but maybe it is not possible to pass more than one parameters to an anonymous function that should be applied groupwise to a data.frame

I have a data.frame

w <- c("A", "B")
x <- c(1,2)
y <- c(3,4)

df <- data.frame(w,x,y)

Now I want to apply a function to each group (defined by column w) that creates column z by multiplying the columns x and y like

df$z <- ...(list(df$x, df$y), df$w, FUN=function(x,y) {x * y}

Actually, I'm not asking for a concrete answer for the multiplication, I'm asking for the syntax how to apply two or more parameters to an anonymous function.

I changed the example due to the correct comment from Joshua, that tapply will not work with a list.

Any hints appreciated

Tom

Upvotes: 0

Views: 1008

Answers (2)

Matthew Plourde
Matthew Plourde

Reputation: 44614

If I understand you correctly, this would be one way:

do.call(mapply, c(function(x, y) x * y, df[-1]))
# [1] 3 8

The number of columns in your data.frame (after removing, say, an ID column) will have to match the number of arguments in the anonymous function.

Or if you want to specify the columns explicitly:

mapply(function(x,y) x * y, df$x, df$y)

Upvotes: 4

Jilber Urbina
Jilber Urbina

Reputation: 61154

Not understand why using anonymous user-defined functions when you can use built-in functions as Reduce or apply with either * or prod. Considering this data.frame:

  w x y
1 A 1 3
2 B 2 4
3 A 3 6
4 A 4 1
5 B 5 2

> Reduce("*", df[,-1])
[1]  3  8 18  4 10

> apply(df[,-1], 1, prod)
[1]  3  8 18  4 10

Upvotes: 2

Related Questions