I'm working my way through the Titanic Study in Frank Harrell's R Flow course (http://hbiostat.org/rflow/case.html) and have a question about summarizing data. The raw data (Titanic5.csv) can be downloaded from https://hbiostat.org/data/repo/titanic5.csv He uses data.table (d is a data.table) to summarize the dataset as follows:
# Create a function that drops NAs when computing the mean
# Note that the mean of a 0/1 variable is the proportion of 1s
mn <- function(x) mean(x, na.rm=TRUE)
# Create a function that counts the number of non-NA values
Nna <- function(x) sum(! is.na(x))
# This is for generality; there are no NAs in these examples
d[, .(Proportion=mn(survived), N=Nna(survived)), by=sex] # .N= # obs in by group
The result of the last command is:
sex Proportion N
1: female 0.7274678 466
2: male 0.1909846 843
Even more interesting is
d[, .(Proportion=mn(survived), N=Nna(survived)), by=.(sex,class)]
which gives
sex class Proportion N
1: female 1 0.9652778 144
2: male 1 0.3444444 180
3: male 2 0.1411765 170
4: female 2 0.8867925 106
5: male 3 0.1521298 493
6: female 3 0.4907407 216
The results are exactly what I want,but the syntax depends very strongly on the capabilities of data.table. How can I get the same results using a dataframe instead of a data table, ideallly with base R, but also with dplyr?
Sincerely
Thomas Philips