how to convert character time to numeric value in R

时间:2017-06-09 12:40:25

标签: r

I have following column in r data frame in character format

 time
 12:45:34
 01:23:00
 21:32:00
 56:32:00

I want it in following format

 time
 12.45
 1.23
 21.32
 56.32

I did following

 gsub("*\\:[0-9]", ".", df$time)

But,does not give what is intended.

2 个答案:

答案 0 :(得分:1)

We can capture the numbers (\\d+) from the start (^) as a group ((..)) followed by : followed by another set of numbers as a group, then in the replacement use the backreference of the captured group and dot in between

df1$time <- as.numeric(sub("^(\\d+):(\\d+).*", "\\1.\\2", df1$time))
df1$time
#[1] 12.45  1.23 21.32 56.32

Or get the substring with substr and replace the ":" with ., convert to numeric

as.numeric(sub(":", ".", substr(df1$time, 1, 5)))

答案 1 :(得分:0)

您可以将字符拆分为:,然后根据需要进行连接。我会采用第二种方法

数据

times = c("12:45:34", "01:23:00", "21:32:00", "56:32:00")

<强> 1

as.numeric(sapply(strsplit(times,":"), function(a) paste(a[1:2], collapse = ".")))
#[1] 12.45  1.23 21.32 56.32

<强> 2

sapply(strsplit(times,":"), function(a)
    as.numeric(a[1]) + as.numeric(a[2])/60 + as.numeric(a[3])/3600)
#[1] 12.759444  1.383333 21.533333 56.533333