: , % , aggregate(), :
> df2 <- within(df, pcLate <- 100 * (1 / Size))
> df2
Date Class Size Sex MinsLate pcLate
1 2010-11-12 Stats 30 M 1 3.333333
2 2010-11-12 Stats 30 M 1 3.333333
3 2010-11-12 Stats 30 M 1 3.333333
4 2010-11-15 Stats 40 F 3 2.500000
5 2010-11-15 Stats 40 F 3 2.500000
6 2010-11-15 Stats 40 F 3 2.500000
7 2010-11-16 Radar 22 M 2 4.545455
8 2010-11-16 Radar 22 M 2 4.545455
9 2010-11-16 Radar 22 M 2 4.545455
10 2010-11-16 Radar 22 M 2 4.545455
11 2010-11-16 Radar 22 M 2 4.545455
> with(df2, aggregate(pcLate, by = list(Date = Date, Class = Class), sum))
Date Class x
1 2010-11-16 Radar 22.72727
2 2010-11-12 Stats 10.00000
3 2010-11-15 Stats 7.50000
:
Assuming it dfcontains the sample data that you provide, we can do this in a couple of steps usingaggregate()
First, take the number of students with a delay in class:
summ <- with(df, aggregate(MinsLate, by = list(Date = Date, Class = Class),
FUN = length))
names(summ)[3] <- "nLate"
What gives us this starting point
> head(summ)
Date Class nLate
1 2010-11-16 Radar 5
2 2010-11-12 Stats 3
3 2010-11-15 Stats 3
Then form the class dimensions:
summ$Size <- with(df, aggregate(Size, by = list(Date = Date, Class = Class),
FUN = unique)$x)
What awaits us:
> head(summ)
Date Class nLate Size
1 2010-11-16 Radar 5 22
2 2010-11-12 Stats 3 30
3 2010-11-15 Stats 3 40
Then calculate the percentage later:
summ <- within(summ, pcLate <- 100 * (nLate / Size))
Result:
> head(summ)
Date Class nLate Size pcLate
1 2010-11-16 Radar 5 22 22.72727
2 2010-11-12 Stats 3 30 10.00000
3 2010-11-15 Stats 3 40 7.50000
If you need to do this a lot, wrap it in a function
tardiness <- function(df) {
out <- with(df, aggregate(MinsLate, by = list(Date = Date, Class = Class),
FUN = length))
names(out)[3] <- "nLate"
out$Size <- with(df, aggregate(Size, by = list(Date = Date, Class = Class),
FUN = unique)$x)
out <- within(out, pcLate <- 100 * (nLate / Size))
out
}
It takes all the steps for us:
> tardiness(df)
Date Class nLate Size pcLate
1 2010-11-16 Radar 5 22 22.72727
2 2010-11-12 Stats 3 30 10.00000
3 2010-11-15 Stats 3 40 7.50000