如何在 R 中创建唯一时间
How to create only time in R
我的数据框中有一个时间列,它的格式是字符:
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
.
感谢您的帮助。
您可以从时间中删除毫秒数。
df <- transform(df, TIME = sub('\..*', '', TIME))
df
# TIME
#1 10:54:10
#2 10:54:11
#3 10:56:34
#4 11:57:11
在使用 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))
我们可以使用 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))
我的数据框中有一个时间列,它的格式是字符:
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
.
感谢您的帮助。
您可以从时间中删除毫秒数。
df <- transform(df, TIME = sub('\..*', '', TIME))
df
# TIME
#1 10:54:10
#2 10:54:11
#3 10:56:34
#4 11:57:11
在使用 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))
我们可以使用 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))