steph
steph

Reputation: 137

How to run functions and ignore missing values, but not whole observation?

I have missing values for a lot of cases and the code below only gives means for Days that have values for all the variables. newsap <- na.omit(sap) seems to omit the whole observation and not just the individual missing values. Is there something I can do to get the means even though there are some missing cases?

aggregate(cbind(BattV, Ptemp, Temp,RH, VPD)~Day,data=subset(sap,Time>=12 & Time<=14),mean)

Date    Day Time    Species Chamber BattV   Ptemp   Temp    RH  VPD 
6/14/10 165 12  1   1   12.92   30.09                       
6/14/10 165 12.1    1   1   12.93   30.57                       
6/14/10 165 12.2    1   1   12.93   31.12                       
6/14/10 165 12.3    1   1   12.93   31.55                       
6/14/10 165 12.4    1   1   12.93   31.72                       
6/14/10 165 12.5    1   1   12.93   31.79                       
6/14/10 165 13  1   1   12.92   31.76                       
6/14/10 165 13.1    1   1   12.92   31.69                       
6/14/10 165 13.2    1   1   12.91   31.62                       
...
7/19/10 200 11.1    1   1   12.09   27.4    30.35       72.688
7/19/10 200 11.2    1   1   12.09   27.72   30.541      70.128
7/19/10 200 11.3    1   1   12.09   27.94   30.279      70.775
7/19/10 200 11.4    1   1   12.09   28.2    30.638      71.988
7/19/10 200 11.5    1   1   12.09   28.62   30.67       69.848

Upvotes: 3

Views: 5154

Answers (1)

Gavin Simpson
Gavin Simpson

Reputation: 174813

In this case, see ?mean and note the na.rm argument. You can pass extra arguments on the aggregated function via ... in ?aggregate, so we can specify na.rm = TRUE in the function call:

aggregate(cbind(BattV, Ptemp, Temp,RH, VPD) ~ Day, 
          data=subset(sap,Time>=12 & Time<=14),
          mean, na.rm = TRUE)

Upvotes: 3

Related Questions