I have a data frame with times.
a <- c("00:51:00", "01:51:00")
b <- c("rando1", "rando2")
d <- c("06:20:00", "06:20:00")
e <- data.frame(a,b,d)
e$a <- hms(e$a) # convert times into lubridate objects
e$d <- hms(e$d)
So e
now looks like this:
a b d
1 51M 0S rando1 6H 20M 0S
2 1H 51M 0S rando2 6H 20M 0S
fun <- function(temp){
#browser() # temp doesn't look like what its supposed to
temp[["a"]] - temp[["d"]]
}
apply(e, 1, fun)
I want to simply subtract column d and column a for each row but inside fun
temp looks like this:
a b d
"51M 0S" "rando1" "6H 20M 0S"
So I can't just use the format parameter to get it back into a lubridate object easily. While reproducing this example I found that a different problem occurs if I call the following line:
apply(e[,c("a","d")], 1, fun) # inside a and d are always 0?
This implies to me that apply is casting the lubridate objects to strings because of the presence of the string column.
It seems like two solutions would work for me. One is to figure out how to make lubridate turn the first entry into "0H 28M 0S"
so that the formatting is constant. The second, which seems like it should exist, is for lubridate to recognize the format and cast back from string to date-time object.
If neither of these are possible I'll go back to investigating using do.call as recommended here to not cast the times into strings. From the link it seems like since all columns aren't the same type apply isn't a good candidate:
Sometimes apply will work - as when all args are of the same type so coercing the data.frame to a matrix does not cause problems by changing data types. Your example was of this sort.