Reputation: 18530
I am attempting to create a list of matrices containing iid Normal numbers. For the sake of a simple example, let the matrices be 4 by 2 and consider a list of length 3. The following code seemed like it should work (to me):
MyMatrix <- lapply(1:3, function() {matrix(rnorm(8), 4, 2)})
But it failed, with the following error:
Error in FUN(1:3[[1L]], ...) : unused argument (1:3[[1]])
On a whim, I tried:
MyMatrix <- lapply(1:3, function(x) {matrix(rnorm(8), 4, 2)})
And it worked! But why? x
is not used anywhere in the function, and on experimentation, the behaviour of the expression is not affected by whether x
already exists in the workspace or not. It appears to be entirely superfluous.
I am new to R, so I would be very grateful if an experienced user could explain what is going on here and why my first line fails.
Upvotes: 3
Views: 837
Reputation: 93813
You can't have a function that doesn't take arguments and then pass it arguments. Which is exactly what you are doing when you run lapply
, as each value is passed in turn as the first argument to the function. E.g.
out <- lapply(1:3, function(x) x)
str(out)
#List of 3
# $ : int 1
# $ : int 2
# $ : int 3
Simple example throwing an error:
test <- function() {"woot"}
test()
#[1] "woot"
test(1)
#Error in test(1) : unused argument (1)
lapply(1:3, test)
#Error in FUN(1:3[[1L]], ...) : unused argument (1:3[[1]])
It's good form for R to error out, as it likely means you're expecting the function's returned result to change based on the arguments passed to the function. And it wouldn't. There are functions like this included in base R, like Sys.time()
, which will fail if you try to pass it superfluous arguments which might otherwise make sense:
Sys.time()
#[1] "2014-07-07 13:22:11 EST"
Sys.time(tz="UTC")
#Error in Sys.time(tz = "UTC") : unused argument (tz = "UTC")
Upvotes: 4