0

I need to write a function to calculate the average annual temperature. I have data for each month's temperature from 1880 to 2017 and need a vector that displays each of the 138 average temperatures. This is what I have tried, I know it's not a lot and not very good but I am very new to this so bear with me:

average <- function(x) {
  if(any(is.na(x)))
    stop("x is missing values")
  c(mean(x[,1:138]))
}
sapply(gistemp.new[2:13],average)

The gistemp.new is the name I gave for the data frame and the first column is just the year. It is like this:

Year   Jan   Feb   Mar   Apr   May   Jun
1   1880 -0.29 -0.18 -0.11 -0.19 -0.11 -0.23
2   1881 -0.15 -0.17  0.04  0.04  0.02 -0.20
3   1882  0.15  0.15  0.04 -0.18 -0.16 -0.26
4   1883 -0.31 -0.39 -0.13 -0.17 -0.20 -0.12
  • Please share the format of data. – MKR Mar 04 '18 at 22:40
  • See my answer here https://stackoverflow.com/questions/49037858/compute-daily-month-and-annual-average-of-several-data-sets/49039111#49039111 – Tung Mar 04 '18 at 22:44

1 Answers1

0
df1 <- read.table(text="Year   Jan   Feb   Mar   Apr   May   Jun
1   1880 -0.29 -0.18 -0.11 -0.19 -0.11 -0.23
2   1881 -0.15 -0.17  0.04  0.04  0.02 -0.20
3   1882  0.15  0.15  0.04 -0.18 -0.16 -0.26
4   1883 -0.31 -0.39 -0.13 -0.17 -0.20 -0.12",h=T,strin=F)

rowMeans(df1[-1])
#           1           2           3           4 
# -0.18500000 -0.07000000 -0.04333333 -0.22000000
moodymudskipper
  • 46,417
  • 11
  • 121
  • 167