0

Hello there :) I'm using the CO2 data set contained within R.

   Plant        Type  Treatment conc uptake
1    Qn1      Quebec nonchilled   95   16.0
2    Qn1      Quebec nonchilled  175   30.4
3    Qn1      Quebec nonchilled  250   34.8
4    Qn1      Quebec nonchilled  350   37.2
5    Qn1      Quebec nonchilled  500   35.3
6    Qn1      Quebec nonchilled  675   39.2
7    Qn1      Quebec nonchilled 1000   39.7
8    Qn2      Quebec nonchilled   95   13.6
9    Qn2      Quebec nonchilled  175   27.3
10   Qn2      Quebec nonchilled  250   37.1
11   Qn2      Quebec nonchilled  350   41.8
12   Qn2      Quebec nonchilled  500   40.6
13   Qn2      Quebec nonchilled  675   41.4
14   Qn2      Quebec nonchilled 1000   44.3
15   Qn3      Quebec nonchilled   95   16.2
16   Qn3      Quebec nonchilled  175   32.4
17   Qn3      Quebec nonchilled  250   40.3
18   Qn3      Quebec nonchilled  350   42.1
19   Qn3      Quebec nonchilled  500   42.9
20   Qn3      Quebec nonchilled  675   43.9
21   Qn3      Quebec nonchilled 1000   45.5

I was wondering if anyone knew if there was an easy way to get the mean uptake for each corresponding concentration(conc) and turn this into a new data frame? I cant figure it out without making a ton of subsets and then combining it.

uthie
  • 11
  • 3
  • You can proceed as [here](http://stackoverflow.com/questions/1660124/how-to-sum-a-variable-by-group) and use `mean` instead of `sum` – talat Jun 02 '16 at 08:48

2 Answers2

3

Using the dplyr approach to execute a split-apply-combine strategy :

library(dplyr)
CO2 %>% group_by(conc) %>% summarize(mean_uptake = mean(uptake))

You can read it as "take CO2 data, group by 'conc', summarize uptake by computing 'mean' as a new variable called mean_uptake"

The result is a tbl_df, a data frame with a nice display in the console

ArunK
  • 1,731
  • 16
  • 35
DianeBeldame
  • 156
  • 6
3

We can use aggregate from base R

 aggregate(uptake~conc, df1, FUN=mean)

Or with data.table

library(data.table)
setDT(df1)[, .(Mean_uptake = mean(uptake), by = conc]
akrun
  • 874,273
  • 37
  • 540
  • 662