diff --git a/lab3/assignment2.R b/lab3/assignment2.R index 0f0353db865508bce261626f6f9d3cc1d67b78ca..8ee408dac5313709b86e5b42bb950330ea3b493f 100644 --- a/lab3/assignment2.R +++ b/lab3/assignment2.R @@ -32,7 +32,7 @@ times <- c( st$time <- strptime(st$time, format = "%H:%M:%S") gaussian_kernel <- function(x, h) { - exp(-(x ^ 2) / (2 * h ^ 2)) + exp(-(x^2) / (2 * h^2)) } x = seq(0, 300000, length.out = 1000) @@ -66,7 +66,6 @@ plot( grid() date_diff_ignoring_year <- function(date1, date2) { - # Generate new dates with the same year date1 <- strsplit(date1, "-")[[1]] date2 <- strsplit(date2, "-")[[1]] @@ -78,10 +77,22 @@ date_diff_ignoring_year <- function(date1, date2) { date2 <- as.Date(paste("2000", month2, day2, sep = "-")) # Get difference in days - diff <- abs(as.numeric(date1-date2)) - + diff <- abs(as.numeric(date1 - date2)) + # If difference is greater than half a year, go other way - if (diff >= 183) diff <- 366 - diff + if (diff >= 183) + diff <- 366 - diff + + return(diff) +} + +difftime_ignoring_day <- function(time1, time2) { + # Get difference in hours + diff <- abs(as.numeric(difftime(time1, time2, units = "hours"))) + + # If difference is grater than 12 hours, go other way + if (diff > 12) + diff <- abs(diff - 24) return(diff) } @@ -96,8 +107,9 @@ for (time in times) { # Filter out posterior dates and time st_temp <- st[st$date < date | (st$date == date & - st$time <= time), ] + st$time < time), ] + # Normalize data? distance_kernels <- mapply(function(lat, lon) { dist <- distHaversine(c(a, b), c(lat, lon)) @@ -112,7 +124,7 @@ for (time in times) { time_kernels <- mapply(function(time_i) { - dist <- as.numeric(difftime(time, time_i, units = "hours")) + dist <- difftime_ignoring_day(time, time_i) gaussian_kernel(dist, h_time) }, st_temp$time)