0

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)
aaaaa
  • 149
  • 2
  • 18
  • 44

2 Answers2

1
x <- NULL
for (i in seq_along(lst1)){
  x[[i]] <- t.test(lst1[[i]]$rainfall, lst2[[i]]$rainfall)
}
x
lizzie
  • 606
  • 6
  • 15
  • When giving an answer it is preferable to give [some explanation as to WHY your answer](http://stackoverflow.com/help/how-to-answer) is the one. – Stephen Rauch Feb 12 '17 at 01:16
0

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)
Tonio Liebrand
  • 17,189
  • 4
  • 39
  • 59