我的数据框中有一个时间列,其格式是字符:
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
.
感谢每一个帮助。
最佳答案
在使用 str_remove
删除最后两位数字后,我们可以使用 chron
包中的 times
#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))
关于r - 如何在R中仅创建时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68950873/