Epoch in R Programming Language
Here’s the translated code and explanation in R, formatted in Markdown suitable for Hugo:
A common requirement in programs is getting the number of seconds, milliseconds, or nanoseconds since the Unix epoch. Here’s how to do it in R.
To run the program, save it as epoch.R
and use Rscript
:
In R, we use Sys.time()
to get the current time. The as.numeric()
function can be used to convert this time to seconds since the Unix epoch. To get milliseconds or nanoseconds, we multiply this value by 1000 or 1e9 respectively.
To convert back from seconds or nanoseconds since the epoch to a time object, we use as.POSIXct()
with the origin
parameter set to “1970-01-01” (the Unix epoch).
Note that R doesn’t have built-in functions for milliseconds or nanoseconds precision like some other languages, so we perform the conversion manually.
Next, we’ll look at another time-related task: time parsing and formatting.