0

I have .csv file with data for three columns i.e., T_avg, T_max and T_min. I am using following code in R to calculate mean of one column i.e., T_Avg

df <- read.csv("G:/Data.csv", header = T)
df <- mutate(df, Date = dmy(Date),Month = month(Date),Year = year(Date))
df <- group_by(df, Year, Month)
df <- summarise(df, result = mean(T_avg)) 
write.csv(df, 'G:/Data_avg.csv')

Now, I want to calculate mean of all the columns (T_avg, T_max, T_min) together in the same code?

I tried following things but it didn't work.

df <- summarise(df, result = mean(T_avg, T_max, T_min))

and

df <- summarise(df, result = mean(T_avg), result = mean(T_max), result = mean(T_min))

I want output csv to have three columns T_avg_mean, T_max_mean and T_min_mean with the mean of T_avg, T_max and T_min, respectively. Could anyone please help me in modifying the code to get the desired output.

  • something like `summarise_at(c("T_avg", "T_max", "T_min"), mean, na.rm = TRUE)` should work. more examples: https://dplyr.tidyverse.org/reference/summarise_all.html – Wimpel Jun 28 '23 at 13:10
  • 2
    @Wimpel the `***_at/_if/_all` functions have been superseded by `across()` since version 1.0 (May 2020). `summarize(df, across(c(T_avg, T_max, T_min), mean))` is the current approach. Or `summarize(df, across(starts_with("T_"), mean))` – Gregor Thomas Jun 28 '23 at 14:01
  • (Or since this isn't grouped, the simple base solution `colMeans(df[c("T_avg", "T_max", "T_min")])` would work just fine) – Gregor Thomas Jun 28 '23 at 14:03

0 Answers0