2

UCBAdmissions is a BASE R dataset in the array format.

I was wondering how I could reformat UCBAdmissions to become a data.frame as shown in the picture below in BASE R?

I have tried the following without success:

as.data.frame.table(UCBAdmissions)

Desired data.frame output:

enter image description here

rnorouzian
  • 7,397
  • 5
  • 27
  • 72

2 Answers2

3

After creating the dataset with as.data.frame.table, can reshape into 'wide' format

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
akrun
  • 874,273
  • 37
  • 540
  • 662
  • @rnorouzian you can do that. I was just thinking that there are dupes and have to take care of that with sequence created with `ave` – akrun Apr 21 '20 at 18:52
2

Convert UCBAdmissions to an ftable and then use ftable2df from this SO answer Reshaping an array to data.frame to convert it to a data.frame. Finally compute the totals. Only base R is used.

transform(ftable2df(ftable(UCBAdmissions, row.vars = 3:2)), 
  Applications = Admitted + Rejected)

giving:

   Dept Gender Admitted Rejected 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
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341