2016-09-07 12 views
0

現在、私はRと闘い、時間差を日数で計算しています。Rの時間差を計算する

私は約60,000行のdata.frameを持っています。このデータフレームには、「開始」および「終了」と呼ばれる2つの列がある。両方の列には、最後の3桁で表示されるように、ミリ秒単位のUNIX時間形式のデータが含まれています。

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

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

d <- data.frame(Start, End) 

希望する出力は、時間差が日で表される余分な列timediffである必要があります。

ここで見つけたタイムディフとstrptimeで試しました。しかし、何もうまくいかなかった。 あなたのうちの1人が、過去の時差の計算に取り組んでいるのかもしれません。 どうもありがとう

答えて

0

あなたが取る必要がありますいくつかのステップがあります。便宜上、すべての機能

# 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") 
} 

そして、とにこれらを配置するのが良いでしょう

# 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") 

をあなたは日々の違いを得ることができます

#* 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