-1

wood is my dataframe

town    date   prec        TP      TC
TR  1/10/1983   NaN       NaN   11.34
CR  2/12/1983   NaN       NaN    4.3
TR  3/12/1983   11.22   11.36    NAN
SP  5/6/1985    NaN       NaN    3.2
BM  6/7/1994    6.33     6.23    1.2
BM  5/6/1995    5.81      5.9    NAN
BM  1/11/2005   5.9       5.9    6.2

I want to get seasonal mean (average) of my data for each town separately. In the past I have used zoo function to find seasonal mean per year for prec. But Zoo has a hard time accepting another variable of town. Now I want to extend it to find seasonal average for “prec,TP, TC” by town per year So for Jan feb march average for 1983 and

May,jun,july average for 1985

Output should look like that. Also “R should not take NAN as zeros”. That is just missing data.

town  date     prec    TP     TC
TR    1983    11.22 11.36   7.82
SP    1985     6.07  6.07   2.2
Gregor Thomas
  • 136,190
  • 20
  • 167
  • 294
Wis786
  • 53
  • 8

1 Answers1

2
library(data.table)
library(lubridate)    
setDT(dat)
dat[ , .(prec = mean(prec, na.rm = T), TP = mean(TP, na.rm = T), TC = mean(TC, na.rm = T))., by = .(town, year(date))]
Kristofersen
  • 2,736
  • 1
  • 15
  • 31
  • I think there is some comma error Error: unexpected symbol in "dt[ , .(prec = mean(prec, na.rm = T), TP = mean(TP, na.rm = T), TC = mean(TC, na.rm = T))." Also it will give me mean for whole year rather than seasonal mean for a year. In the past I have extracted month by using following function month= function (x) as.numeric(format(x, "%m"))prec1 <-which(month(tt) %in% 1:3). not working on this dat – Wis786 Feb 16 '17 at 19:58
  • So i wrote this to follow your output You coudl also add month(date) to get the mean by month, by year, and by town. I fixed the typo that was in there. – Kristofersen Feb 16 '17 at 20:00
  • @Wisconsin you should take some time to learn data.table, that would solve a lot of the questions you've been asking. Also, you should mark your questions as solved when you get the answer you're looking for. – Kristofersen Feb 16 '17 at 20:01
  • 1
    I think you could do [something like this](http://stackoverflow.com/a/13666870/903061) to apply to all the columns at once. With 3 columns it's not too bad, but if you had more... – Gregor Thomas Feb 16 '17 at 22:32
  • 1
    Thanks Code worked now. @Kristofersen I think practicing with data.table was a good suggestion. – Wis786 Feb 17 '17 at 22:59
  • Awesome, glad you got it working. Datacamp has a great intro if you want to keep learning and there's a cheat sheet on data.table that has a ton of helpful examples. – Kristofersen Feb 17 '17 at 23:00