Reputation: 11
I have a data frame of dates from 2013 to 2018, with a daily precipitation value for a location I am studying. I want to calculate the mean precipitation of each date for the years mentioned above. For example, the mean precipitation on June 1 from 2013 to 2018. I will use this daily mean to then study the daily deviations from the mean daily precipitation from 2013 to 2018.
This is what my data looks like DataTable
I don't know how to write the loop for this, so I don't have any code to show.
The output for this loop should be a list of dates of the year with a long term mean for each date, something like below:
Date (dd/mm) Mean
01-01 1.5
02-01 4.6
03-01 5
.
.
31-12 6
Thank you!
Upvotes: 1
Views: 76
Reputation: 8572
This has been answered in a plethora of other posts. A combination of
would answer your question.
I'll assume your dataTable is actually either a data.table
or data.frame
, and or shorthand I'll call the data data
. I'll provide a base
R version using with
and ave
function, and i'll provide an example with data.table
using their subsetting option
library(lubridate)
library(data.table)
#Data frame way
with(data, ave(Vil_481690, #variable to calculate mean
year(Vil_dates), #which variables to group (can be any number of variables)
FUN = mean #already standard
))
#data.table way
setDT(data) #change data to a data.table
data[, mean(Vil_481690), by = year(Vil_dates)])]
Note these have not been tested as there was no copy-able data, so there might be typo one place or another.
Upvotes: 1