I have a dataframe that looks something like this:
dat <- data.frame("posix_time" = as.POSIXct(c("2021-07-01 01:00:00 CEST", "2021-07-01 01:10:00 CEST", "2021-07-01 01:20:00 CEST",
"2021-07-01 01:30:00 CEST", "2021-07-01 01:40:00 CEST", "2021-07-01 01:50:00 CEST",
"2021-07-01 02:00:00 CEST", "2021-07-01 02:10:00 CEST", "2021-07-01 02:20:00 CEST")),
"value" = c(5, 8, 15, 7, 12, 5, 89, 1, 17))
Now I want to get the index or in this case data of "value" directly using the which-function. Doing it like this works fine:
temp <- dat$value[which(dat$posix_time >= "2021-07-01 01:00:00" & dat$posix_time <= "2021-07-01 02:00:00")]
This should then be written into a pre defined matrix of a certain size:
mat <- matrix(NA, ncol = 15, nrow = 1)
Where ncol is a number of timesteps. Here it would be:
colnames(mat) <- c("00:00", "00:10", "00:20", "00:30", "00:40", "00:50", "01:00", "01:10", "01:20", "01:30", "01:40", "01:50", "02:00", "02:10", "02:20")
Now I would like to write the value into the matrix that corresponds to the correct time from dat
. But I am not sure how to do that.
It should look like this:
00:00 00:10 00:20 00:30 00:40 00:50 01:00 01:10 01:20 01:30 01:40 01:50 02:00 02:10 02:20
NA NA NA NA NA NA 5 8 15 7 12 5 89 NA NA
dat <- dat[which(dat$posix_time >= "2021-07-01 01:00:00" & dat$posix_time <= "2021-07-01 02:00:00"), ]
mat[match(gsub("^.* (\\d{2}:\\d{2}).*$", "\\1", dat$posix_time), colnames(mat))] <- dat$value
# 00:00 00:10 00:20 00:30 00:40 00:50 01:00 01:10 01:20 01:30 01:40 01:50 02:00 02:10 02:20
#[1,] NA NA NA NA NA NA 5 8 15 7 12 5 89 NA NA