kaji331 kaji331 - 3 months ago 14
R Question

How to get mean by name in R

I get a csv file has data like below:

> "value","name"
> 403.375,"C1"
> 409.625,"C1"
> 300.5,"C11"
> 321.125,"C11"
> 740.25,"C2"
> 718.875,"C2"
> 303.25,"Q"
> 323,"Q"
> 146.875,"H1"
> 171.75,"H1"
> 210.875,"H2"
> 234.625,"H2"
> 1640,"CQ1"
> 1742.5,"CQ1"
> 2319.875,"CH1"
> 2449,"CH1"
> 1227.25,"CH2"
> 1157.375,"CH2"
> 781,"CQ1.1"
> 715.125,"CQ1.1"
> 713.125,"CH1.1"
> 670.25,"CH1.1"


How can I get the mean of values by names, like this:

> "mean","name"
> 406.5,"C1"
> 310.8125,"C11"
> ... ...


and get the barplot to show mean labels by name in R?

Answer

data <- read.csv('data.csv')

data

      value  name
1   403.375    C1
2   409.625    C1
3   300.500   C11
4   321.125   C11
5   740.250    C2
6   718.875    C2
7   303.250     Q
8   323.000     Q
9   146.875    H1
10  171.750    H1
11  210.875    H2
12  234.625    H2
13 1640.000   CQ1
14 1742.500   CQ1
15 2319.875   CH1
16 2449.000   CH1
17 1227.250   CH2
18 1157.375   CH2
19  781.000 CQ1.1
20  715.125 CQ1.1
21  713.125 CH1.1
22  670.250 CH1.1
> tapply(data$value, data$name, mean)
       C1       C11        C2       CH1     CH1.1       CH2       CQ1     CQ1.1 
 406.5000  310.8125  729.5625 2384.4375  691.6875 1192.3125 1691.2500  748.0625 
       H1        H2         Q 
 159.3125  222.7500  313.1250