'How to use apply() on an array of matrices in R?

I am trying to use apply() on an array of matrices. Here is an example:

data(UCBAdmissions)
fisher.test(UCBAdmissions[,,1]) #This works great
apply(UCBAdmissions, c(1,2,3), fisher.test) #This fails


Solution 1:[1]

Something like this: Personally I do it this way: First make a list UCB_list

then bind list elements to dataframe with rbindlist from data.table

finally, use lapply indicating the column y=df$Gender you want to iterate through:

library(data.table)
UCB_list <- list(UCBAdmissions)
df <- rbindlist(lapply(UCB_list, data.frame))

lapply(df, fisher.test, y = df$Gender)
> lapply(df, fisher.test, y = df$Gender)
$Admit

    Fisher's Exact Test for Count Data

data:  X[[i]] and df$Gender
p-value = 1
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
 0.1537975 6.5020580
sample estimates:
odds ratio 
         1 


$Gender

    Fisher's Exact Test for Count Data

data:  X[[i]] and df$Gender
p-value = 7.396e-07
alternative hypothesis: true odds ratio is not equal to 1
95 percent confidence interval:
 16.56459      Inf
sample estimates:
odds ratio 
       Inf 


$Dept

    Fisher's Exact Test for Count Data

data:  X[[i]] and df$Gender
p-value = 1
alternative hypothesis: two.sided


$Freq

    Fisher's Exact Test for Count Data

data:  X[[i]] and df$Gender
p-value = 0.4783
alternative hypothesis: two.sided

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 TarJae