-1

Hello can you help me with difference in (hours) in R from one column. I use only basic package R. I would like to create new column with hours so the column look like

hours<-c(0,24,23,21,31,26,28)

time<-c('10. 4. 2018 10:16:11', 
'11. 4. 2018 10:16:15', 
'12. 4. 2018 10:13:31',
'13. 4. 2018 8:16:31', 
'14. 4. 2018 15:16:21',
'15. 4. 2018 17:16:31', 
'16. 4. 2018 19:15:31')

I have one colum (time) and i would like to create new column (hours)

thanks

Uwe
  • 41,420
  • 11
  • 90
  • 134
dado
  • 79
  • 5

2 Answers2

1

Enhancing Sotos' approach,

c(0, round(diff(as.POSIXct(time, format = '%d. %m. %Y %H:%M:%S'), units = "hours")))

comes close to OP's expected result

[1]  0 24 24 22 31 26 26

Data

time <- c(
  '10. 4. 2018 10:16:11',
  '11. 4. 2018 10:16:15',
  '12. 4. 2018 10:13:31',
  '13. 4. 2018 8:16:31',
  '14. 4. 2018 15:16:21',
  '15. 4. 2018 17:16:31',
  '16. 4. 2018 19:15:31'
)
Community
  • 1
  • 1
Uwe
  • 41,420
  • 11
  • 90
  • 134
0

Another way is the following.

First coerce to class POSIXct.

time <- as.POSIXct(time, format = "%d. %m. %Y %H:%M:%S")

Now use difftime, it will give the result in the required units.

c(0, difftime(time[-1], time[-length(time)]))
#[1]  0.00000 24.00111 23.95444 22.05000 30.99722 26.00278 25.98333

The rounded output is simple to obtain.

round(c(0, difftime(time[-1], time[-length(time)])))
#[1]  0 24 24 22 31 26 26
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66