Skip to content

Instantly share code, notes, and snippets.

@nataliamd11
Created July 30, 2018 22:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nataliamd11/96e746bcffbd251d3bc8fdaec72badbf to your computer and use it in GitHub Desktop.
Save nataliamd11/96e746bcffbd251d3bc8fdaec72badbf to your computer and use it in GitHub Desktop.
HourlyToDaily-function that obtain daily data from hourly data
HourlyToDaily <- function(data.x, ncol.obs, ncol.date, na.presence = TRUE, value = "mean") {
#
if (!any(value == c("mean", "accumulated"))) {
stop(" value must to be 'mean' or 'accumulated'")
}
# Calculate the mean of the variable of interest
first.year <- min(data.x$year, na.rm = na.presence)
last.year <- max(data.x$year, na.rm = na.presence)
x.daily.per.years <- list()
date.tot <- list()
c = 1
# Creates a temporary i data.frame for each year == i
for (i in first.year:last.year) {
x.anual <- data.x[data.x$year == i, ]
# It takes the i year df and creates a j df for each month == j
first.month = min(x.anual$month, na.rm = na.presence)
last.month = max(x.anual$month, na.rm = na.presence)
x.daily.per.month <- list()
date.list <- list()
for (j in first.month:last.month) {
x.month <- x.anual[x.anual$month == j, ]
# It takes the j month df and creates a k df for each day == k
first.day = min(x.month$day, na.rm = na.presence)
last.day = max(x.month$day, na.rm = na.presence)
x.value.max <- list()
x.value.min <- list()
x.value <- list()
date.x <- list()
for (k in first.day:last.day) {
x.day <- x.month[x.month$day == k, ]
# Calculates the mean value or the accumulated value
if (all(unlist(lapply(X = x.day[ , ncol.obs], FUN = is.na)))) {
x.value[k] <- NA
} else {
if (value == "mean") {
x.value.max[k] <- max(x.day[ , ncol.obs], na.rm = na.presence)
x.value.min[k] <- min(x.day[ , ncol.obs], na.rm = na.presence)
x.value[k] <- mean(x = c(x.value.max[[k]], x.value.min[[k]]), na.rm = na.presence)
} else {
x.value[k] <- sum(x.day[ , ncol.obs], na.rm = na.presence)
}
}
date.x[k] <- x.day[ , ncol.date][1]
} # end cycle day
x.daily.per.month[[j]] <- unlist(x.value)
date.list[[j]] <- date.x
} # end cycle month
x.daily.per.years[[c]] <- unlist(x.daily.per.month)
date.tot[[c]] <- unlist(date.list)
c = c + 1
daily.data <- as.data.frame(unlist(x.daily.per.years))
daily.data <- cbind.data.frame(unlist(date.tot), daily.data)
colnames(daily.data) <- c("date", "value")
daily.data$date <- as.Date.numeric(daily.data$date, origin = "1970-01-01")
}
return(daily.data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment