Search code examples
rlistdataframet-test

Perform Student's t-test between data.frames contained in two lists


I have got two separate lists which contain 4 data.frames each one. I need to perform a Student's t-test (t.test) for rainfall between each data.frames within the two lists.

Here the lists:

lst1 = list(data.frame(rnorm(20), rnorm(20)), data.frame(rnorm(25), rnorm(25)), data.frame(rnorm(16), rnorm(16)), data.frame(rnorm(34), rnorm(34)))    
lst1 = lapply(lst1, setNames, c('rainfall', 'snow'))

lst2 = list(data.frame(rnorm(19), rnorm(19)), data.frame(rnorm(38), rnorm(38)), data.frame(rnorm(22), rnorm(22)), data.frame(rnorm(59), rnorm(59)))
lst2 = lapply(lst2, setNames, c('rainfall', 'snow'))

What I would need to do is:

t.test(lst1[[1]]$rainfall, lst2[[1]]$rainfall)
t.test(lst1[[2]]$rainfall, lst2[[2]]$rainfall)
t.test(lst1[[3]]$rainfall, lst2[[3]]$rainfall)
t.test(lst1[[4]]$rainfall, lst2[[4]]$rainfall)

I can do it as above by writing each of the 4 data.frames (I actually have 40 with my real data) but I would like to know if there exists a smarter and quickier way to do it.

Here below what I tried (without success):

myfunction = function(x,y) {
  test = t.test(x, y)
  return(test)
}

result = mapply(myfunction, x=lst1, y=lst2)

Solution

  • Works for me. I would use simplify = FALSE to get the results formatted better though.

    lst1 <- list()
    lst1[[1]] <- data.frame(rainfall = rnorm(10))
    lst1[[2]] <- data.frame(rainfall = rnorm(10))
    lst2 <- list()
    lst2[[1]] <- data.frame(rainfall = rnorm(10))
    lst2[[2]] <- data.frame(rainfall = rnorm(10))
    
    myfunction = function(x,y) {
      test = t.test(x$rainfall, y$rainfall)
      return(test)
    }
    
    mapply(myfunction, x = lst1, y = lst2, SIMPLIFY = FALSE)