gpt4 book ai didi

r - 将数组操作为 BASE R 中的 data.frame

转载 作者:行者123 更新时间:2023-12-02 09:03:22 25 4
gpt4 key购买 nike

UCBAdmissions 是数组格式的 BASE R 数据集。

我想知道如何在 BASE R 中将 UCBAdmissions 重新格式化为如下图所示的 data.frame?

我已经尝试了以下但没有成功:

as.data.frame.table(UCBAdmissions)

所需的 data.frame 输出:

enter image description here

最佳答案

使用as.data.frame.table创建数据集后,可以reshape为'wide'格式

out <- as.data.frame.table(UCBAdmissions)
out$rn <- with(out, ave(seq_along(Admit), Admit, Gender, Dept, FUN = seq_along))
out1 <- transform(reshape(out, idvar = c("Gender", "Dept", "rn"),
direction = 'wide', timevar = 'Admit'),
applications = Freq.Admitted + Freq.Rejected)[, c(2, 1, 4:6)]
names(out1)[1:4] <- c('dept', 'applicant.gender', 'admit', 'reject')
row.names(out1) <- NULL
out1
# dept applicant.gender admit reject applications
#1 A Male 512 313 825
#2 A Female 89 19 108
#3 B Male 353 207 560
#4 B Female 17 8 25
#5 C Male 120 205 325
#6 C Female 202 391 593
#7 D Male 138 279 417
#8 D Female 131 244 375
#9 E Male 53 138 191
#10 E Female 94 299 393
#11 F Male 22 351 373
#12 F Female 24 317 341

关于r - 将数组操作为 BASE R 中的 data.frame,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61333663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com