Jamie Leigh Jamie Leigh - 1 month ago 8
R Question

Separating three dimensional array by the stratifying variable

I am working with the UCBAdmissions data set, and I want to separate out the data set into the 6 departmental tables that you get when you simply run

>UCBAdmissions
, , Dept = A

Gender
Admit Male Female
Admitted 512 89
Rejected 313 19

, , Dept = B

Gender
Admit Male Female
Admitted 353 17
Rejected 207 8

, , Dept = C

Gender
Admit Male Female
Admitted 120 202
Rejected 205 391

, , Dept = D

Gender
Admit Male Female
Admitted 138 131
Rejected 279 244

, , Dept = E

Gender
Admit Male Female
Admitted 53 94
Rejected 138 299

, , Dept = F

Gender
Admit Male Female
Admitted 22 24
Rejected 351 317


I am pretty sure I can make the data set into a dataframe and then go through and grep by department and sum to make tables, but I am wondering if there is an easier way, sine the data is already set up in the exact format I want, I just need to handle each department table individually

Answer

Oh, sorry I misread your question. You are not looking for converting this into a data frame but for splitting.

You may use:

setNames(lapply(1:dim(UCBAdmissions)[3], function (i) UCBAdmissions[,,i]),
         dimnames(UCBAdmissions)[[3]])

#A
#          Gender
#Admit      Male Female
#  Admitted  512     89
#  Rejected  313     19
#
#$B
#          Gender
#Admit      Male Female
#  Admitted  353     17
#  Rejected  207      8
# 
#$C
#          Gender
#Admit      Male Female
#  Admitted  120    202
#  Rejected  205    391
# 
#$D
#          Gender
#Admit      Male Female
#  Admitted  138    131
#  Rejected  279    244
# 
#$E
#          Gender
#Admit      Male Female
#  Admitted   53     94
#  Rejected  138    299
# 
#$F
#          Gender
#Admit      Male Female
#  Admitted   22     24
#  Rejected  351    317
Comments