Someone sent me the following code, which repeats the same command (mvrnorm) 10 times, in a list format.
dat <- lapply(1:10,mvrnorm, n = 10, Sigma=matrix(.3, 3, 3), mu = rep(0, 3))
The code works.
However, when I try the following command, it did not work and I do not understand why it does not work. I expect it to count the number of columns in 'x' ten times repeatedly:
dat <- lapply(1:10, ncol, x=matrix(.3, 4, 4))
Error in FUN(X[[i]], ...) : unused argument (X[[i]])
Basically, I am trying to understand in what situation the following format works:
lapply(1:10, function, ...)
If anyone can explain to me why it works when the function is mvrnorm
(first example) but not ncol
(second example)?
lapply() function is used with a list and performs operations like: sapply(List, length): Returns the length of objects present in the list, List. sapply(List, sum): Returns the sum of elements held by objects in the list, List. sapply(List, mean): Returns the mean of elements held by objects in the list, List.
Explanation: lapply() always returns a list, regardless of the class of the input.
Format of an lapplylapply returns a list as it's output. In the output list there is one component for each component of the input list and it's value is the result of applying the function to the input component.
The apply functions (apply, sapply, lapply etc.) are marginally faster than a regular for loop, but still do their looping in R, rather than dropping down to the lower level of C code. For a beginner, it can also be difficult to understand why you would want to use one of these functions with their arcane syntax.
How to reproduce that error with as few lines as possible in R:
test = function(){ #method takes no parameters
print("ok")
}
lapply(1:10, test) #passing in 1 through 10 into test,
#error happens here
Throws the error:
Error in FUN(X[[i]], ...) : unused argument (X[[i]])
Calls: lapply -> FUN
Execution halted
The method 'test' takes no arguments, and you passed 1 argument to it with lapply.
How to fix it:
Make sure the function passed to sapply takes the same number of arguments that you are feeding it:
test = function(foobar){ #method takes one parameter
print("ok")
}
lapply(1:10, test) #passing in 1 through 10 into test,
#this runs correctly, printing ok 10 times.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With