Reputation: 1
I'm using Rstudio version 1.10.136 in Mac OS Sierra 10.12.2 and here's what I want to do. I have a set of data and I created a data frame and then I filtered it after removing the NA and it looks like this:
Date sulfate nitrate ID
279 2003-10-06 7.2100 0.6510 1
285 2003-10-12 5.9900 0.4280 1
291 2003-10-18 4.6800 1.0400 1
297 2003-10-24 3.4700 0.3630 1
303 2003-10-30 2.4200 0.5070 1
Now I want to calculate the mean based on ID call such as:
mean("specdata_subset", "sulfate", 1:10)
or
mean("specdata_subset", "nitrate", 40)
How do I write a general function that helps me calculate mean based on the ID numbers.
Upvotes: 0
Views: 54
Reputation: 1610
Use aggregate()
:
aggregate(nitrate~ID, df, mean)
aggregate(sulfate~ID, df, mean)
Data:
df <- read.table(text = '
Date sulfate nitrate ID
279 2003-10-06 7.2100 0.6510 1
285 2003-10-12 5.9900 0.4280 1
291 2003-10-18 4.6800 1.0400 1
297 2003-10-24 3.4700 0.3630 1
303 2003-10-30 2.4200 0.5070 1')
Upvotes: 1