我有一个数据帧,它在列运行时中有持续时间。
>df
value runtime info
1 129 4:52:05 sample1
3 145 1-5:12:43 sample2我不确定如何正确地将这些持续时间转换为可排序的格式,例如使用dplyr arrange。
如果我使用下面的代码,我会得到一个稍微正确且可排序的持续时间,但日期不是必需的,而且这只适用于%d-%H:%M:%S,%H:%M:%S的持续时间不能正确读取,需要单独处理。
>strptime('1-5:12:43',format='%d-%H:%M:%S')
[1] "2018-12-01 5:12:43 CET"lubridate包中有一个duration函数,但无法指定持续时间的输入格式。
我想我可以想出一个聪明的正则表达式语句来将运行时字符串分解成它的位,以便像这样使用它:
>duration(second = 3, minute = 1.5, hour = 2, day = 6)然而,在我这样做之前,也许还有其他更简单的建议?
发布于 2018-12-05 20:06:06
您也可以对字符串进行排序,但字符串和各个组件的宽度需要固定。不过,您需要执行一些字符串操作。我看不到任何其他实用的方法:
rtimes<-c('1-5:12:43','4:52:05','32:05','2-23:59:59')
sortable<-sapply(rtimes,function(str){
s<-as.numeric(
unlist(
strsplit(str,'-|:')
)
)
v<-c(rep.int(0,4-length(s)),s) # Padding the vector to ensure 4 components
paste(formatC(v,width = 2,flag = '0'),collapse = ' ') # PAdding the components to ensure 2 digits
},USE.NAMES = F)
sortable
[1] "01 05 12 43" "00 04 52 05" "00 00 32 05" "02 23 59 59"
sort(sortable)
"00 00 32 05" "00 04 52 05" "01 05 12 43" "02 23 59 59"发布于 2018-12-05 19:27:38
也许你可以在进行转换之前,在没有日期值的运行时前加上"0-“?例如,通过这样做:
df$runtime[!grepl("-", df$runtime)] <- paste0(
"0-", df$runtime[!grepl("-", df$runtime)])之后,您可以对时间进行排序。
https://stackoverflow.com/questions/53630848
复制相似问题