Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About the use of lapply

Tags:

for-loop

r

lapply

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)?

like image 856
Chet Avatar asked Oct 16 '15 05:10

Chet


People also ask

What is Lapply and Sapply in R?

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.

Which statement is true about Lapply function?

Explanation: lapply() always returns a list, regardless of the class of the input.

Does Lapply return a list?

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.

Is Lapply faster than for loop?

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.


1 Answers

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.
like image 128
Eric Leschinski Avatar answered Sep 25 '22 00:09

Eric Leschinski