次のデータフレームでは、「時間」列は次character
の形式になっていますhour:minute:second
id <- c(1, 2, 3, 4)
time <- c("00:00:01", "01:02:00", "09:30:01", "14:15:25")
df <- data.frame(id, time)
'time'列を専用の時間クラスに変換して、算術計算を実行するにはどうすればよいですか?
chron
パッケージ内の関数を使用しますchron
:
time<-c("00:00:01", "01:02:00", "09:30:01", "14:15:25")
library(chron)
x <- chron(times=time)
x
[1] 00:00:01 01:02:00 09:30:01 14:15:25
連続する要素間の差を計算するなど、いくつかの便利なことを行います。
diff(x)
[1] 01:01:59 08:28:01 04:45:24
chron
オブジェクトは、値を1日あたりの秒の端数として内部に保存します。1/(60*60*24)
したがって、1秒は、、または1/86400
、つまりに相当し1.157407e-05
ます。
したがって、時間を追加するための1つの簡単なオプションは次のとおりです。
x + 1/86400
[1] 00:00:02 01:02:01 09:30:02 14:15:26
base R を使用すると、それを class のオブジェクトに変換できますがPOSIXct
、これは時刻に日付を追加します。
id<-c(1,2,3,4)
time<-c("00:00:01","01:02:00","09:30:01","14:15:25")
df<-data.frame(id,time,stringsAsFactors=FALSE)
as.POSIXct(df$time,format="%H:%M:%S")
[1] "2012-08-20 00:00:01 CEST" "2012-08-20 01:02:00 CEST"
[3] "2012-08-20 09:30:01 CEST" "2012-08-20 14:15:25 CEST"
しかし、それはそれらに対して算術計算を実行することを可能にします。
別の可能な代替手段は次のとおりです。
time <- c("00:00:01","01:02:00","09:30:01","14:15:25")
converted.time <- as.difftime(time, units = "mins") #"difftime" class
secss <- as.numeric(converted.time, units = "secs")
hourss <- as.numeric(converted.time, units = "hours")
dayss <- as.numeric(converted.time, units="days")
あるいは:
w <- strptime(x = time, format = "%H:%M:%S") #"POSIXlt" "POSIXt" class
パッケージ内のITime
クラスを使用する:data.table
ITime
1 日の整数秒数として格納される時刻クラスです。
library(data.table)
(it <- as.ITime(time))
# [1] "00:00:01" "01:02:00" "09:30:01" "14:15:25"
it + 10
# [1] "00:00:11" "01:02:10" "09:30:11" "14:15:35"
diff(it)
# [1] "01:01:59" "08:28:01" "04:45:24"