From 97024f7ab10350c933897333c48e2428847c76f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20Ramnel=C3=B6v?= <felra653@student.liu.se> Date: Fri, 20 Dec 2024 10:56:12 +0100 Subject: [PATCH] Lab 3: Fixes for assignment 2, according to seminar --- lab3/assignment2.R | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/lab3/assignment2.R b/lab3/assignment2.R index 0f0353d..8ee408d 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) -- GitLab