How to use lapply with a formula?

I have a problem with the lapply function, and I did not find any matching question published earlier. I need to apply a permutation test to all elements of a list, however I cannot configure lapply correctly.

I'm trying this

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

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

Any hints on how to apply such a function would be greatly appreciated. Jens

+8
list r lapply
source share
2 answers

When you use a formula, you often also need to specify a value for the data argument so that the function knows which data to use. Your datasets will be list items, so you need to use an anonymous function to provide them in perm.test.

In this case, try:

 testperm <- lapply(test.list, FUN=function(x) perm.test(formula=(cover ~ group),data=x)) 
+9
source share

This is your third argument that you need to look at.

lapply takes (at least) two arguments, a list (including a data frame) and a FUN function that runs 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 the FUN and not provided by the data string of the first argument:

 lapply( df0[,1], quantile, probs=1:3/4) 
+2
source share

All Articles