[R] Outputting a difftime object in PASTE or AS.CHARACTER is missing the unit + expand the format options?

Reuver, B de (epi) b@de@reuver @end|ng |rom umcg@n|
Wed Oct 23 10:11:50 CEST 2024


Hello,

I was working on an R script using the datediff object, to log certain durations in the data processing.
I ran in to the issue that outputing a datediff object using PASTE will leave out the time unit by default.

When you paste() or as.character() a datediff object it only outputs the numeric value, for example "1.23", so without the time unit secs, minutes, hours etc. This is arguably is not very useful, because 1.23 seconds is very different from 1.23 hours.

```
start_time <- Sys.time()
result <- sum(1:10000)
dur_time <- Sys.time() - start_time

print(paste(Sys.time(), "the process duration:", dur_time)) # "2024-10-23 09:57:10.69578 the process duration: 0.00280904769897461"

print(dur_time)               # "Time difference of 0.002809048 secs"
print(paste(dur_time))        # "0.00280904769897461"
print(as.character(dur_time)) # "0.00280904769897461"
print(format(dur_time))       # "0.002809048 secs"

print(paste(dur_time, attr(dur_time, "units"))) # "0.00280904769897461 secs"
```

So my questions are:
1)  is it possible to have the default output for as.character for the datediff object also include the time unit? That way, it automatically outputs for example "1.23 seconds" when used in combination with paste().
If someone really need just the numeric value without the unit, you can already use as.numeric(dur_time).
2) Is it possible to expand the format() options for the datediff object, so that it also accepts a strptime-like string, so like %H:%M:%S ? That way you have more output options without having to rely on third-party libraries

regards,
Bas de reuver (UMCG, The Netherlands)
________________________________
 De inhoud van dit bericht is vertrouwelijk en alleen bestemd voor de geadresseerde(n). Anderen dan de geadresseerde(n) mogen geen gebruik maken van dit bericht, het niet openbaar maken of op enige wijze verspreiden of vermenigvuldigen. Het UMCG kan niet aansprakelijk gesteld worden voor een incomplete aankomst of vertraging van dit verzonden bericht.

The contents of this message are confidential and only intended for the eyes of the addressee(s). Others than the addressee(s) are not allowed to use this message, to make it public or to distribute or multiply this message in any way. The UMCG cannot be held responsible for incomplete reception or delay of this transferred message.



More information about the R-help mailing list