This seems to be sub-setting a data.frame and converting it to a data.table
W_Objectives <- as.data.table(W_Objectives)[ , mean(Result) , list(AnalyteName , BeneficialUse , UnitName , StationCode , ProjectName , SampleDate , MatrixName , FractionName , TargetLatitude , TargetLongitude , Waterbody , WBID , Wbtype , Objective , AveragingPeroid , Objective_Language , Evaluation_Guideline , Objective_Ref_Number , Eval_Ref_Number , Comment)]
I am not sure how it works. I very seldomly use data.table so I may be missing something but I do not see how one can calculate mean(Result) while converting the data.frame.
names(W_Objectives)[names(W_Objectives)=='V1'] <- "Result"
Here you appear to renaming the first variable in the data table but I am not sure if the syntax works
W_Objectives <- tbl_df(W_Objectives)
Now you are converting the data.table back into a data.frame---essentially a tibble is a data.frame. As far as I can see the conversion to and from a data.table is redundant.
I am trying to pull specific data out of my dataframe to average on a monthly basis instead. I did this like so:
monthlymean <- W_Objectives[W_Objectives$Comment == "monthly mean" , ]
monthlymean <- monthlymean %>%
mutate(
year=year(SampleDate) , # extract partslibrary(lubridate)
month=month(SampleDate)
)
I am lost. You appear to be pulling something out of the comment column but without seeing some raw data I don't understand what is happening. I am pretty sure that you cannot use mutate here.
Here, very roughly is what I think your code is doing in very simple form.
library(tidyverse)
library(data.table)
library(lubridate)
dat1 <- data.frame(aa = letters[1:5],
bb = 1:5,
cc = 5:1,
dd = LETTERS[5:1])
dtb1 <- as.data.table(dat1[, c("aa", "bb", "cc", "dd")])
tibb1 <- tibble(dtb1)
What you seem to be trying to do with the dates is
tt1 <- ymd("2020-09-12", "2021-08-05")
tt2 <- year(tt1)
class(tt2)
mean(tt2)
I do not think that is what you intended.
Some data would be nice. Please have a look at