round function in R

I am trying to round a timestamp to the nearest seconds I am using the round function. It gives me the following error message: Error in function_list[k] :
3 arguments passed to 'round'which requires 1 or 2 arguments.
Many Thanks

df %>%
  select(timestamp)%>%
  round(timestamp, digits=2)

data sample

 1 2018-11-08T07:41:55.921Z
 2 2018-11-08T07:42:29.842Z
 3 2018-11-08T07:42:29.845Z
 4 2018-11-08T07:42:29.845Z
 5 2018-11-08T07:43:13.957Z
 6 2018-11-08T07:43:56.239Z
 7 2018-11-08T07:43:56.239Z
 8 2018-11-08T07:43:57.223Z
 9 2018-11-08T07:44:47.555Z
10 2018-11-08T07:45:20.713Z

Hi user124578, I think you need to reformat your timestamp in a time format (POSIXct) that R can deal with...

So based on your data samples and your timestamps :wink: :

dat.times <- c("2018-11-08T07:41:55.921Z",
               "2018-11-08T07:42:29.842Z",
               "2018-11-08T07:42:29.845Z",
               "2018-11-08T07:42:29.845Z",
               "2018-11-08T07:43:13.957Z",
               "2018-11-08T07:43:56.239Z",
               "2018-11-08T07:43:56.239Z",
               "2018-11-08T07:43:57.223Z",
               "2018-11-08T07:44:47.555Z",
               "2018-11-08T07:45:20.713Z")
#drop 'T' and 'Z' out of your input format
dat.times <- gsub('T|Z',' ', dat.times)
dat.times
#>  [1] "2018-11-08 07:41:55.921 " "2018-11-08 07:42:29.842 "
#>  [3] "2018-11-08 07:42:29.845 " "2018-11-08 07:42:29.845 "
#>  [5] "2018-11-08 07:43:13.957 " "2018-11-08 07:43:56.239 "
#>  [7] "2018-11-08 07:43:56.239 " "2018-11-08 07:43:57.223 "
#>  [9] "2018-11-08 07:44:47.555 " "2018-11-08 07:45:20.713 "

#specify the time format, using %OS to represent the seconds with their fractional parts
dat.times <- as.POSIXct(dat.times, format = "%Y-%m-%d %H:%M:%OS")

#round the milliseconds to seconds
round.POSIXt(dat.times, units='secs')
#>  [1] "2018-11-08 07:41:56 CET" "2018-11-08 07:42:30 CET"
#>  [3] "2018-11-08 07:42:30 CET" "2018-11-08 07:42:30 CET"
#>  [5] "2018-11-08 07:43:14 CET" "2018-11-08 07:43:56 CET"
#>  [7] "2018-11-08 07:43:56 CET" "2018-11-08 07:43:57 CET"
#>  [9] "2018-11-08 07:44:48 CET" "2018-11-08 07:45:21 CET"

As note: Try to use reprex(), see https://forum.posit.co/t/5219
It's quite a cool tool to post your questions to the R-communtiy. It's helps us to help you! :slight_smile:

4 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.