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.
You could use
dcast
ofreshape2
to convert output of SymbolixAU's answer to your liking.Or you could do it in base R too but would be relatively more complex
DATA