0

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.

emschorsch
  • 1,619
  • 3
  • 19
  • 33
  • 1
    Could you please share a minimal reproducible example? –  Oct 08 '15 at 04:54
  • These look like string representation of lubridate's Period objects. There is no direct way to transform Date object into Period object. You can cast Date as numeric and feed that to `as.period`, although I wasn't able to get results similar to yours this way. Also, I've never seen `apply` changing data.frame into matrix. I find it very unlikely since `apply` will reduce number of dimensions in data structure. There is not much to be done without [minimal reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) that Pascal asked for. – Mirek Długosz Oct 08 '15 at 07:39
  • Added a minimal example. For some reason I thought the problem was easy to induce but coming up with a minimal example showed me I was wrong. – emschorsch Oct 08 '15 at 14:37

0 Answers0