Rich Scriven
Rich Scriven

Reputation: 99321

Reproducing the result from Map() with mapply()

Take the following data frame and vector,

df <- data.frame(x = 1:3, y = 4:6, z = 7:9)
v <- c(5, 10, 15)

Assume I want to multiply df columnwise by the elements of v, meaning df[1] * v[1], df[2] * v[2], and df[3] * v[3]

I can do this with Map

> Map(`*`, df, v)
$x
[1]  5 10 15

$y
[1] 40 50 60

$z
[1] 105 120 135 

Now, since Map is defined as

> Map
function (f, ...) 
{
    f <- match.fun(f)
    mapply(FUN = f, ..., SIMPLIFY = FALSE)
}
<bytecode: 0x3950e00>
<environment: namespace:base>

it seems logical that I should be able to reproduce the above exactly with the following call to mapply, but this is not the case.

> mapply(`*`, df, v, simplify = FALSE)
# Error in .Primitive("*")(dots[[1L]][[1L]], dots[[2L]][[1L]],   
#   simplify = dots[[3L]][[1L]]) : operator needs one or two arguments

The problem seems to be within the arguments of "*", and those arguments are

> args("*")
function (e1, e2) 
NULL

So two more tries yield similar errors.

> mapply(`*`, e1 = df, e2 = v, simplify = FALSE)
# Error in .Primitive("*")(e1 = dots[[1L]][[1L]], e2 = dots[[2L]][[1L]],  : 
#   operator needs one or two arguments
> mapply(`*`, ..1 = df, ..2 = v, simplify = FALSE)
# Error in .Primitive("*")(..1 = dots[[1L]][[1L]], ..2 = dots[[2L]][[1L]],  : 
#   operator needs one or two arguments

What is the issue here? And how can I reproduce (exactly) the result from

Map(`*`, df, v)

with mapply?

Upvotes: 4

Views: 416

Answers (1)

MrFlick
MrFlick

Reputation: 206167

Notice that Map calls

mapply(FUN = f, ..., SIMPLIFY = FALSE)

not

mapply(FUN = f, ..., simplify = FALSE)

and of course R is case sensitive. Try

mapply(`*`, df, v, SIMPLIFY = FALSE)
# $x
# [1]  5 10 15
# 
# $y
# [1] 40 50 60
# 
# $z
# [1] 105 120 135

instead. With simplify = FALSE, it's trying to call

`*`(df[[1]], v[1], simplify = FALSE)

which is what is giving that error.

Upvotes: 6

Related Questions