Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use lapply with a formula?

Tags:

list

r

lapply

I have a problem with the lapply function and I did not find any matching question posted earlier. I need to apply a permutation test to all list elements, however I am not able to setup the lapply correctly.

I am trying this

testperm <- lapply(test-list, FUN=perm.test, formula=(cover ~ group))

the function perm.test is from the package 'exactRankTests' cover is the dependent (numerical) variable and group is a factor.

Any hints on how to apply such a function would be very much appreciated. jens

like image 726
Jens Avatar asked Aug 10 '11 10:08

Jens


People also ask

What is the purpose of the Lapply () function?

The lapply() function helps us in applying functions on list objects and returns a list object of the same length. The lapply() function in the R Language takes a list, vector, or data frame as input and gives output in the form of a list object.

What is the difference between Lapply and Sapply?

Difference between lapply() and sapply() functions:lapply() function displays the output as a list whereas sapply() function displays the output as a vector. lapply() and sapply() functions are used to perform some operations in a list of objects.

What does apply () do in R?

apply() function apply() takes Data frame or matrix as an input and gives output in vector, list or array. Apply function in R is primarily used to avoid explicit uses of loop constructs. It is the most basic of all collections can be used over a matrice.


2 Answers

When you use a formula, you often also need to supply a value to a data argument so the function knows which data to use. You data sets will be the list elements, so you need to use an anonymous function to supply them to perm.test.

In this case try:

testperm <- lapply(test.list, FUN=function(x) perm.test(formula=(cover ~ group),data=x)) 
like image 140
James Avatar answered Oct 03 '22 13:10

James


It's your third argument that you need to take a look at.

lapply takes (at least) two arguments, a list (incl. data frame) and a function, FUN, that operates on it:

data(iris)
df0 = iris[1:5,1:3]

fnx = function(v){v^2}

lapply(df0, fnx)

lapply accepts an optional third argument which must correspond to additional arguments required by FUN and not furnished by lapply's first argument data structure:

lapply( df0[,1], quantile, probs=1:3/4)
like image 45
doug Avatar answered Oct 03 '22 13:10

doug