How can I convert the duration so it appears as the number of days?
As an other solution we could utilize difftime
, e. g.:
unitnames = c(week="weeks", weeks="weeks", day="days", days="days", hour="hours", hours="hours",
minute="mins", minutes="mins", second="secs", seconds="secs")
converdays =
function(w)
{ sapply(strsplit(w, ", "), # for each string, separate the quantities by ", "
function(x)
do.call(sum, # sum up the duration quantities, computed such:
lapply(strsplit(x, " "), # split into magnitude and unit
function(y) # convert to a "difftime" with that unit
{ z = as.difftime(as.integer(y[1]), units=unitnames[y[2]])
units(z)="days" # change that unit to the desired "days"
return(z)
}
)
)
)
}
converdays(Duration_1)
# [1] 3.027911e+02 1.388889e-04 2.358796e-02 7.920139e-02 3.824074e-02
converdays(Duration_2)
# [1] 6.365741e-04 8.865741e-01 2.032581e+00 5.785648e-01 1.112341e+02
Another variant, should one prefer the output to keep the class difftime
in order to be able to easily convert to different units, is:
unitnames = c(week ="weeks", day ="days", hour ="hours", minute ="mins", second ="secs",
weeks="weeks", days="days", hours="hours", minutes="mins", seconds="secs")
csplit = function(x, s, f) do.call(c, lapply(strsplit(x, s), f)) # helper function to split
convertds = function(w) # convert to difftimes
csplit(w, ", ", # for each string, separate the quantities by ", "
function(x)
sum(csplit(x, " ", # split into magnitude and unit, convert and sum up
function(y) as.difftime(as.integer(y[1]), units=unitnames[y[2]]))))
print (convertds(Duration_1) -> d1)
# Time differences in secs
# [1] 26161153 12 2038 6843 3304
units(d1)="days"
d1
# Time differences in days
# [1] 3.027911e+02 1.388889e-04 2.358796e-02 7.920139e-02 3.824074e-02