2016-09-07 145 views
0

我目前正在用R掙扎並計算天數的時間差。計算R中的時間差

我有大約60 000行data.frame。在這個數據框中有兩列稱爲「開始」和「結束」。兩列都包含UNIX時間格式的毫秒數據 - 正如您在前三位數字中所看到的那樣。

Start <- c("1470581434000", "1470784954000", "1470811368000", "1470764345000") 

End <- c("1470560601000", "1470581549000", "1470785452000", "1470764722000") 

d <- data.frame(Start, End) 

我想要的輸出應該是一個額外的列,名爲timediff,其中時間差異以大概天數爲單位。

我試着用我在這裏找到的timediff和strptime。但沒有解決。 也許你們中的一個人在過去計算時間差異。 非常感謝

回答

0

你有你需要採取一些步驟:

# 1. Separate the milliseconds. 
# To do this, insert a period in front of the last three digits 

Start <- 
    sub(pattern = "(\\d{3}$)", # get the pattern of three digits at the end of the string 
     replacement = ".\\1", # replace with a . and then the pattern 
     x = Start) 

# 2. Convert to numeric 
Start <- as.numeric(Start) 

# 3. Convert to POSIXct 
Start <- as.POSIXct(Start, 
        origin = "1970-01-01") 

爲方便起見,將是很好的把這些都變成一個功能

# Bundle all three steps into one function 
unixtime_to_posixct <- function(x) 
{ 
    x <- sub(pattern = "(\\d{3}$)", 
      replacement = ".\\1", 
      x = x) 
    x <- as.numeric(x) 
    as.POSIXct(x, 
      origin = "1970-01-01") 
} 

並與那麼,你可以在幾天內得到你的區別

#* Put it all together. 
library(dplyr) 
library(magrittr) 

Start <- c("1470581434000", "1470784954000", "1470811368000", "1470764345000") 

End <- c("1470560601000", "1470581549000", "1470785452000", "1470764722000") 

d <- data.frame(Start, 
       End, 
       stringsAsFactors = FALSE) 

lapply(
    X = d, 
    FUN = unixtime_to_posixct 
) %>% 
    as.data.frame() %>% 
    mutate(diff = difftime(Start, End, units = "days")) 
3

有一個非常小的和快速的解決方案:

Start_POSIX <- as.POSIXct(as.numeric(Start)/1000, origin="1970-01-01") 
End_POSIX <- as.POSIXct(as.numeric(End)/1000, origin="1970-01-01") 
difftime(Start_POSIX, End_POSIX) 

Time differences in mins 
[1] 347.216667 3390.083333 431.933333 -6.283333 

,或者如果你想另一個單位:

difftime(Start_POSIX, End_POSIX, unit = "sec") 

Time differences in secs 
[1] 20833 203405 25916 -377