简体   繁体   中英

difference between columns with time in r

I've a data frame in which there are two columns with in and out time, I'm trying to get the time difference in seconds in another column.

 ` ## intime ##     |s  ## outtime ##

 1. 6/20/2017 1:47  |s  6/20/2017 1:47
 2. 6/20/2017 3:32  |s  6/20/2017 3:32
 3. 6/20/2017 21:45 |s  6/20/2017 21:45
 4. 6/23/2017 0:15  |s 6/23/2017 0:15
 5. 6/17/2017 1:30  |s 6/17/2017 1:30`

I tried using

 `t<-c(m1$intime)
  t1<-c(m1$outime)
  dt <- as.POSIXct(t)
#Error in as.POSIXct.numeric(t) : 'origin' must be supplied
  dt <- as.POSIXct(t1)
#Error in as.POSIXct.numeric(t1) : 'origin' must be supplied`

tried using the code in the link time difference giving error

difftime(t2, t1) Error in as.POSIXlt.character(as.character(x), ...) : character string is not in a standard unambiguous format

not sure where I'm going wrong. The columns are integer type.

Thank you.

There are a couple of problems here.

If your columns are integers, then as.POSIXct will interpret them as the number of seconds since a specific time, which is defined by the origin argument that the error is referencing.

If your columns are characters but not in a standard format, it's necessary to tell as.POSIXct how to interpret the different parts of the character string.

Here is an example from ?as.POSIXct :

as.POSIXct("2011-03-27 01:30:00", format = "%Y-%m-%d %H:%M:%S")

If your columns actually look like "6/20/2017 1:47" , then you should be able to use:

as.POSIXct("6/20/2017 1:47", format = '%m/%d/%Y %H:%M')

or

as.POSIXct(m1$intime, format = '%m/%d/%Y %H:%M')

But it's unclear how your columns can be integers and still look like the table you have posted.

The error says everything you need to move forward. as.POSIX* gives you an error because you don't have the standart date format. Check the function ?strptime . Also, here is a good article about dates in R

> x=c("6/20/2017 1:47")
> library(lubridate)
> y=mdy_hm(x)
> y
[1] "2017-06-20 01:47:00 UTC"

so going by the given data

df1$intime=mdy_hm(df1$intime)
df1$outtime-mdy_hm(df1$outime)
df$timefidd=difftime(df1$intime,df1$outtime,units='secs')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM