I have a dataset consisting on a first column with dates and many other columns mean daily temperature at different sites (depths in this case). Looks like this:
Date DayMean_2cm DayMean_5cm DayMean_80cm DayMean_120cm DayMean_160cm DayMean_200cm DayMean_250cm DayMean_300cm DayMean_350cm DayMean_450cm
1 2019-12-28 19.9 19.9 20.0 20.2 20.0 20.2 20.2 20.1 20.5 20.6
2 2019-12-29 8.76 8.68 8.26 8.30 7.97 8.10 8.07 7.94 8.12 8.17
3 2019-12-30 2.20 1.78 -0.215 -0.294 -0.706 -0.657 -0.725 -0.818 -0.61 -0.414
4 2019-12-31 3.76 3.31 -0.215 -0.294 -0.706 -0.657 -0.725 -0.818 -0.602 -0.414
5 2020-01-01 4.34 3.91 -0.215 -0.294 -0.706 -0.657 -0.725 -0.818 -0.579 -0.398
6 2020-01-02 3.52 3.45 -0.215 -0.255 -0.706 -0.649 -0.694 -0.818 -0.548 -0.367
What i need to calculate using R is the monthly sumation of the positive temperatures, and the negative temperatures... for each column.
I know how to do it column by column using this piece of code:
MonthIndexes <- DayStats2 %>%
group_by(Year, Month) %>%
summarize(MonthFDD = sum(DayMean[which(DayMean<0)]), MonthTDD = sum(DayMean[which(DayMean>0)]))
it works nicely, but i would like to do it for all the columns at once, independently of the number of columns contained in the dataset. If fact i do other calculations in that fashion with this piece of code:
MonthStats <- data %>%
group_by(Year, Month) %>%
summarise(across(
.cols = is.numeric,
.fns = list(MonthMean=mean, MonthMax=max, MonthMin=min, MonthSD=sd), na.rm = TRUE,
.names = "{fn}_{col}"
))
However, my problems it that i do not know how to adapt the last piece of code to calculate the conditional summation. I tried this without good results:
MonthIndexes <- DayStats2 %>%
group_by(Year, Month) %>%
summarise(across(
.cols = is.numeric,
.fns = list(MonthFDD = sum({col}[which({col}<0)]), MonthTDD=sum({col}[which({col}>0)])), na.rm = TRUE,
.names = "{fn}_{col}"
))
The error returned in RStudio is
Error: Problem with
summarise()
input..1
. i..1 = across(...)
. x comparison (3) is possible only for atomic and list types
Any help will be appreciated. Thanks in advance.