Find Mean in Each Group

143 views Asked by At

Within each group, I want to find the mean for two sub-groups. To be clear, the data looks like the following:

Group Val1 Val2 Val3
1     50   0.03  50.1
1     50.2 0.05  50.1
2     50.3 0.01  50.1
1     50   0.03  50.2
1     50.1 0.04  50.2
1     50   0.01  50.3
1     50   0.02  50.3
2     50.3 0.03  50.3

Within each group in Val3, I want to calculate the mean of Val2 in Group 1 and the mean of Val2 in Group 2. In some cases, for Val3, there are no members in Group 2. This is the code I attempted.

fileB.mean.dat <- tapply(combined.sorted.data[combined.sorted.data[,1] == 2,3], combined.sorted.data[combined.sorted.data[,1] == 2,4], mean)

I don't know how to include in the code above to check for whether there are members of group 2 and if not to make the mean 0 for Val 3. In other words, there should be a representative mean value for Group 1 and 2 for every value of Val 3.

2

There are 2 answers

0
d.b On BEST ANSWER

You could use dcast of reshape2 to convert output of SymbolixAU's answer to your liking.

library(reshape2)
dcast(data = aggregate(Val2 ~ Group + Val3, data = df, mean),
      formula = Group~Val3,
      value.var = "Val2")
#  Group 50.1  50.2  50.3
#1     1 0.04 0.035 0.015
#2     2 0.01    NA 0.030

Or you could do it in base R too but would be relatively more complex

sapply(split(df[c("Group", "Val2")], df$Val3),
       function(a) sapply(unique(df$Group),
            function(x) setNames(mean(a$Val2[a$Group == x]), x)))
#  50.1  50.2  50.3
#1 0.04 0.035 0.015
#2 0.01   NaN 0.030

DATA

df = structure(list(Group = c(1, 1, 5, 1, 1, 1, 1, 5), Val1 = c(50, 
50.2, 50.3, 50, 50.1, 50, 50, 50.3), Val2 = c(0.03, 0.05, 0.01, 
0.03, 0.04, 0.01, 0.02, 0.03), Val3 = c(50.1, 50.1, 50.1, 50.2, 
50.2, 50.3, 50.3, 50.3)), .Names = c("Group", "Val1", "Val2", 
"Val3"), row.names = c(NA, -8L), class = "data.frame")
2
akrun On

We can use tidyverse

library(tidyverse)
df %>% 
   group_by(Group, Val3) %>%
   summarise(Val2 = mean(Val2)) %>% 
   spread(Val3, Val2)
# A tibble: 2 x 4
# Groups:   Group [2]
#   Group `50.1` `50.2` `50.3`
#* <dbl>  <dbl>  <dbl>  <dbl>
#1     1   0.04  0.035  0.015
#2     2   0.01     NA  0.030