我有一些mm:ss.00格式的演奏时间数据(即02:15.45或00:34.58).R将变量识别为一个因子,但我想将每个演奏时间转换为几秒(即02:15.45到135.45).我已经找到了答案,但似乎找不到让它工作的方法.提前致谢.
inh*_*kht 22
使用lubridate:
library(lubridate)
period_to_seconds(hms("12:12:54"))
Run Code Online (Sandbox Code Playgroud)
Jef*_*eff 16
这是我多年来一直使用的.它也是矢量化的.
toSeconds <- function(x){
if (!is.character(x)) stop("x must be a character string of the form H:M:S")
if (length(x)<=0)return(x)
unlist(
lapply(x,
function(i){
i <- as.numeric(strsplit(i,':',fixed=TRUE)[[1]])
if (length(i) == 3)
i[1]*3600 + i[2]*60 + i[3]
else if (length(i) == 2)
i[1]*60 + i[2]
else if (length(i) == 1)
i[1]
}
)
)
}
Run Code Online (Sandbox Code Playgroud)
反之(保留所需位数的小数秒:
secondsToString <- function(x,digits=2){
unlist(
lapply(x,
function(i){
# fractional seconds
fs <- as.integer(round((i - round(i))*(10^digits)))
fmt <- ''
if (i >= 3600)
fmt <- '%H:%M:%S'
else if (i >= 60)
fmt <- '%M:%S'
else
fmt <- '%OS'
i <- format(as.POSIXct(strptime("0:0:0","%H:%M:%S")) + i, format=fmt)
if (fs > 0)
sub('[0]+$','',paste(i,fs,sep='.'))
else
i
}
)
)
}
Run Code Online (Sandbox Code Playgroud)
看看strptime.特别
t = "02:15.45"
(as.numeric(as.POSIXct(strptime(t, format = "%M:%OS"))) -
as.numeric(as.POSIXct(strptime("0", format = "%S"))))
Run Code Online (Sandbox Code Playgroud)
这可行,但可能有点尴尬(这样做主要是因为POSIXct的烦人的自动单位转换......)
小智 5
library(lubridate)
df$variable<- hms(df$variable)
df$variable<- as.numeric(df$variable)
Run Code Online (Sandbox Code Playgroud)
让它成为单线也可以。对我来说就像一种魅力。
我希望这有帮助。