Mat*_*dan 13 datetime r type-conversion
我有一个矢量"Time.Training",格式为hours:minutes:seconds(例如
Time.Training<- c("1:00:00", "0:45:00", "0:30:00", "1:30:00")
Run Code Online (Sandbox Code Playgroud)
我想将其转换为以下格式的分钟:
Time.Training.Minutes<-c(60, 45, 30, 90)
Run Code Online (Sandbox Code Playgroud)
我想知道是否有人在R中有一个直截了当的方法.
非常感谢.
马特
tos*_*pig 13
使用lubridate:
Time.Training<- c("1:00:00", "0:45:00", "0:30:00", "1:30:00")
library(lubridate)
res <- hms(Time.Training) # format to 'hours:minutes:seconds'
hour(res)*60 + minute(res) # convert hours to minutes, and add minutes
## [1] 60 45 30 90
Run Code Online (Sandbox Code Playgroud)
Dav*_*urg 11
试试这个.我们基本上POSIXlt首先通过使用Sys.Date()函数将实际日期粘贴到向量来转换为类(因为基本R中没有小时类)然后使用 hour和min参数来实现输出
Res <- as.POSIXlt(paste(Sys.Date(), Time.Training))
Res$hour*60 + Res$min
## [1] 60 45 30 90
Run Code Online (Sandbox Code Playgroud)
使用as.difftime:
> Time.Training<- c("1:00:00", "0:45:00", "0:30:00", "1:30:00")
> strtoi(as.difftime(Time.Training, format = "%H:%M:%S", units = "mins"))
[1] 60 45 30 90
Run Code Online (Sandbox Code Playgroud)
以下是一些替代方案:
1) chron包有一个"times"类,每天1个单位,一天有60*24分钟,所以:
library(chron)
60 * 24 * as.numeric(times(Time.Training))
Run Code Online (Sandbox Code Playgroud)
赠送:
[1] 60 45 30 90
Run Code Online (Sandbox Code Playgroud)
1a)使用chron的另一种方法如下(给出相同的答案):
library(chron)
ch <- times(Time.training)
60 * hours(ch) + minutes(ch)
Run Code Online (Sandbox Code Playgroud)
2)这是一种使用read.table和矩阵/向量乘法的方法.不需要包裹:
c(as.matrix(read.table(text = Time.Training, sep = ":")) %*% c(60, 1, 1/60))
Run Code Online (Sandbox Code Playgroud)
(使用"POSIXlt"可能是没有包的最直接的方法,但另一个答案已经提供了.)
| 归档时间: |
|
| 查看次数: |
38204 次 |
| 最近记录: |