val val - 10 days ago 6
R Question

how to summarize numeric and factor level values simultaneously in R

I'm trying to summarize a dataset by grouping on one column (F1) and getting the average of the other columns, except that the other columns are split between numeric and factor levels. I can use ddply to summarize F2 numeric values but not sure how to do the same for the factor levels in F3. I tried to capture the mos repeated factor level by group but this is not working.

reproducible example

library(plyr)
set.seed(37)
df<-data.frame("F1"=rep(LETTERS[1:5],each = 3),
"F2"= 1:15,
"F3"= sample(c("Yes","No"), 15, replace=TRUE))
df2 <- ddply(df,~F1,summarise,
mF2=mean(F2),
mF3=tail(names(sort(table(df$F3))), 1))
> df
F1 F2 F3
1 A 1 No
2 A 2 Yes
3 A 3 No
4 B 4 Yes
5 B 5 No
6 B 6 No
7 C 7 Yes
8 C 8 Yes
9 C 9 Yes
10 D 10 Yes
11 D 11 Yes
12 D 12 No
13 E 13 Yes
14 E 14 Yes
15 E 15 No
> df2
F1 mF2 mF3
1 A 2 Yes
2 B 5 Yes
3 C 8 Yes
4 D 11 Yes
5 E 14 Yes


Instead, df2 should look like this:

> df2
F1 mF2 mF3
1 A 2 No
2 B 5 No
3 C 8 Yes
4 D 11 Yes
5 E 14 Yes


I'd be keen to try with dplyr or other method if shown how.

Answer

We can use similar option in dplyr

library(dplyr)
df %>% 
  group_by(F1) %>% 
  summarise(mF2 = mean(F2), mF3 = tail(names(sort(table(F3))),1))