8

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

Jens
  • 2,363
  • 3
  • 28
  • 44

2 Answers2

9

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)) 
James
  • 65,548
  • 14
  • 155
  • 193
  • Hi James, that looks useful, however, I receive the error: 'Error in test - list : non-numeric Argument for binary Operator' hence it generally says that 'test-list' does not work? – Jens Aug 10 '11 at 12:02
  • `test-list` contains the minus symbol, which is invalid in variable names unless you use backtick notation, best to rename it `test.list`. I'll modify the answer using this name. – James Aug 10 '11 at 12:08
  • @Gavin Simpson I don't think that will work, because without anonymous functions, lapply only passes to the first argument of a function. – James Aug 10 '11 at 12:10
  • Ah sorry, misunderstood what test-list. You are correct. I'm going to delete my useless comment. – Gavin Simpson Aug 10 '11 at 12:16
  • James, many thanks. Yes, that 'minus' was confusing. Now it works! Great! – Jens Aug 12 '11 at 13:16
2

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)
doug
  • 69,080
  • 24
  • 165
  • 199
  • Hey Doug, thank you, I am aware of this example. It is quite simple. How does this work with a more complex thing like perm.test? – Jens Aug 10 '11 at 12:05