I am new to R, I want to calculate monthly and annual average of sea surface temperature (SST). I get an error in using aggregate function: "NO ROWS IN AGGREGATE". My data: NetCDF file, from November 2004 to May 2022. I have searched that no rows to aggregate could caused by the length of the vector that are not same, but after I try to equalize it, the result still the same. Thank you for your help. What I have done:
#opening file
library(ncdf4)
library(lubridate)
setwd("D:/Data analysis/SST_fg")
nc_fname <- "METOFFICE-GLO-SST-L4-REP-OBS-SST_1679654370682.nc"
nc_ds <- nc_open(nc_fname)
#extracting time and converting to date
dim_time <- ncvar_get(nc_ds, "time")
t_units <- ncatt_get(nc_ds, "time", "units")
t_ustr <- strsplit(t_units$value, " ")
t_dstr <- strsplit(unlist(t_ustr)[3], "-")
date <- ymd(t_dstr) + dseconds(dim_time)
#extracting sst and converting to celcius
suhu <- ncvar_get(nc_ds, "analysed_sst", collapse_degen=FALSE)
suhu = suhu - 273.15
#creating matrix for both time and sst
coords <- as.matrix(expand.grid(date))
temprtr <- as.matrix(expand.grid(suhu))
#equalizing length of vectors
maxlength <- max(length(coords), length(temprtr))
length(coords) <- maxlength
length(temprtr) <- maxlength
#creating dataframe
nc_df <- data.frame(cbind(coords, temprtr))
#calculating monthly average
monthlymean <- aggregate(nc_df$temprtr[!is.na(nc_df$temprtr)],
by = list(date = format(as.Date(nc_df$coords[!is.na(nc_df$temprtr)]),"%Y-%m")), mean, na.rm = TRUE)