r语言 - 用分层变量分离三维阵列



我正在处理UCBAdmissions数据集,我想将数据集分离到您只需运行

时得到的6个部门表中。
>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

我很确定我可以把数据集变成一个数据框架,然后通过部门和总和来制作表格,但我想知道是否有更简单的方法,因为数据已经按照我想要的确切格式设置了,我只需要单独处理每个部门表

哦,对不起,我误解了你的问题。您不是要将其转换为数据帧,而是要进行拆分。

你可以使用:

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

可以在for循环中使用assign:

for (i in 1:6){assign(LETTERS[i], UCBAdmissions[,,i])}
A
#           Gender
# Admit      Male Female
#   Admitted  512     89
#   Rejected  313     19

B, C, D, E, F也是如此

相关内容

  • 没有找到相关文章

最新更新