-2

I would wish to find the average per season for each year. Each year is observed 4 times. The seasons are two but are repeated twice as shown below

year=rep(c(1990:1992),each=4)
season=c("W","D","W","D","W","W","D","D","D","W","W","D")
temp=c(28,25,26,21,28,25,20,20,20,35,28,21)
df=data.frame(year,season,temp)

which gives

   year season temp
1  1990      W   28
2  1990      D   25
3  1990      W   26
4  1990      D   21
5  1991      W   28
6  1991      W   25
7  1991      D   20
8  1991      D   20
9  1992      D   20
10 1992      W   35
11 1992      W   28
12 1992      D   21

i want to collapse this data to have the average of the two seasons for each year as below

  year season avgtemp
1 1990      D    23.0
2 1990      W    27.0
3 1991      D    20.0
4 1991      W    25.1
5 1992      D    20.5
6 1992      W    31.5

How can i obtain this?

Steven Wambua
  • 119
  • 1
  • 6

2 Answers2

0

Try below:

    aggregate(df[, 3], df[, 1:2], mean)
Sonal Borkar
  • 531
  • 1
  • 6
  • 12
0
library(tidyvere) 
df %>% 
     group_by(year,season) %>% 
   summarise(avgtemp=mean(temp))
# A tibble: 6 x 3
# Groups:   year [?]
   year season avgtemp
  <int> <fct>    <dbl>
1  1990 D         23  
2  1990 W         27  
3  1991 D         20  
4  1991 W         26.5
5  1992 D         20.5
6  1992 W         31.5
jyjek
  • 2,627
  • 11
  • 23