【问题标题】:How to create only time in R如何在 R 中只创建时间
【发布时间】:2021-10-27 05:51:00
【问题描述】:
我的数据框中有一个时间列,它的格式是字符:
TIME
10:54:10.23
10:54:11.58
10:56:34.21
11:57:11.23
所以你看到我最后也有毫秒,但我试图只得到 %H-%M-%S 而没有 .x 毫秒。我尝试通过以下方式创建一个新列:data$hms <- format(as.POSIXct(data$TIME), "%H:%M:%S") 但失败了...Error in as.POSIXlt.character(x, tz, ...): String is not in a unique standard format。
感谢每一个帮助。
【问题讨论】:
标签:
r
dataframe
datetime
timestamp
format
【解决方案1】:
我们可以使用来自base R的trimws
df$TIME <- trimws(df$TIME, whitespace = "\\.\\d+")
-输出
df$TIME
[1] "10:54:10" "10:54:11" "10:56:34" "11:57:11"
数据
df <- structure(list(TIME = c("10:54:10.23", "10:54:11.58", "10:56:34.21",
"11:57:11.23")), class = "data.frame", row.names = c(NA, -4L))
【解决方案2】:
我们可以使用chron 包中的times 在用str_remove 删除最后两位数字后使用
#install.packages("chron")
library(chron)
library(dplyr)
library(stringr)
df %>%
mutate(TIME = chron(times=str_remove(TIME, '\\..*$')))
输出:
TIME
<times>
1 10:54:10
2 10:54:11
3 10:56:34
4 11:57:11
数据
df <- structure(list(TIME = c("10:54:10.23", "10:54:11.58", "10:56:34.21",
"11:57:11.23")), class = "data.frame", row.names = c(NA, -4L))
【解决方案3】:
您可以从时间中删除毫秒数。
df <- transform(df, TIME = sub('\\..*', '', TIME))
df
# TIME
#1 10:54:10
#2 10:54:11
#3 10:56:34
#4 11:57:11