Here is subset of my original data I am working with:
dput(datumi)
structure(c("21:26", "21:33", "21:38", "23:02", "23:03", "21:27",
"21:34", "21:39", "23:03", "23:04", "21:26", "21:33", "21:38",
"23:02", "23:04", "21:26", "21:34", "21:38", "23:02", "23:04",
"21:27", "21:34", "21:39", "23:02", "23:04"), .Dim = c(5L, 5L
), .Dimnames = list(c("2", "3", "4", "5", "6"), c("Datum_1",
"Datum_2", "Datum_3", "Datum_4", "Datum_5")))
So I am working with time, where e.g., 21:26 means time of the day.
Now I would like to subtract second column from first one and third from second and so on, this means that I would subtract column Datum_2
from Datum_1
and column Datum_3
from Datum_2
and Datum_4
from Datum_3
. And my output will be new columns with differences in seconds
I've already created function/loop that does this if my data would be numeric
, so for example in case of numeric data I would do this and get the desired output:
dat <- data.frame(
column1 = round(runif(n = 10, min=0, max=5),0),
column2 = round(runif(n = 10, min=0, max=5),0),
column3 = round(runif(n = 10, min=0, max=5),0),
column4 = round(runif(n = 10, min=0, max=5),0)
)
results <- list()
for(i in 1:length(dat)) {
if (i==length(dat)){
results[[i]] <-dat[,i]
} else {results[[i]] <-dat[,i+1] - dat[,i]}
}
results <- t(do.call(rbind,results))
results <- data.frame(results)
But I cannot figure it out for time format and I have tried strptime
and as.POSIXct
x1 <- strptime(datumi, "%H:%M")
as.numeric(x1,units="secs")
and
as.POSIXct(datumi,format="%H:%M")
And also looked at this
Subtracting Two Columns Consisting of Both Date and Time in R