# Re: [R] Calculating a daily average

From: Gavin Simpson <gavin.simpson_at_ucl.ac.uk>
Date: Tue, 22 Jun 2010 09:41:25 +0100

On Mon, 2010-06-21 at 10:27 -0400, ecvetano_at_uwaterloo.ca wrote:
> I have a set of data with 12 readings for temperature per day, with
> 180 days. I want to find the average temperature of each day. I am
> able to do this one by one, but with that many days to calculate the
> average for, it will get very long. I'm sure there is a faster way to
> do this, I just don't know how. What i have so far is:
>
>
> av1 <- subset(ER9r, Day == 98, select = c (Depth1j:Depth0.75j))
> av1 <- mean(av1 [av1>0])
> av2 <- subset(ER9r, Day == 99, select = c (Depth1j:Depth0.75j))
> av2 <- mean(av2 [av2>0])
> av3 <- subset(ER9r, Day == 100, select = c (Depth1j:Depth0.75j))
> av3 <- mean(av3 [av3>0])
> av4 <- subset(ER9r, Day == 101, select = c (Depth1j:Depth0.75j))
> av4 <- mean(av4 [av4>0])
> av5 <- subset(ER9r, Day == 102, select = c (Depth1j:Depth0.75j))
> av5 <- mean(av5 [av5>0])
>
> Depth<- c("SML")
> Day<- c(98, 99, 100, 101, 102)
> Average<- c(av1, av2, av3, av4, av5)
> chlsummaryER9 <- data.frame (Depth, Day, Average)
> chlsummaryER9
>
> Any ideas on how to do this in less steps?

## dummay data
set.seed(123)

```dummy <- data.frame(X = rnorm(20, 4),
Y = rnorm(20, 6),
Z = rnorm(20, 0),
Day = rep(1:4, each = 5))

```

av1 <- mean(subset(dummy, Day == 1, select = c(X,Z)))

## using aggregate do it in one step
av2 <- with(dummy, aggregate(dummy[,c("X","Z")],

```                             by = list(Day = Day), mean))

## to do you mean of positives, we write a simple wrapper to mean()
## which takes argument x (x will refer now to the bits of data that
```
## aggregate feeds our function foo() ), and pass on additional ## arguments to mean via ... such as na.rm foo <- function(x, ...) {

mean(x[x > 0], ...)
}
## we then change the aggregate call to use foo not mean and additional ## arguments are listed after foo, which will get passed to it. av3 <- with(dummy, aggregate(dummy[,c("X","Z")],

```                             by = list(Day = Day), foo, na.rm = TRUE))

```

HTH G

>
> Thanks,
> Emilija
>
> ______________________________________________
> R-help_at_r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> and provide commented, minimal, self-contained, reproducible code.

```--
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%

______________________________________________
R-help_at_r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help