我有一个变量需要转换成军事时间。这个变量非常混乱,因为它在格式上缺乏一致性。
下面是一个可以在变量中找到的例子。
x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 1525")到目前为止,我在用RegEx实现更一致的格式方面取得了一些成功:
x <- str_extract(x, "[0-9]+.+[0-9]|[0-9][0-9][:][0-9][0-9]")
x <- str_remove(x, "[:]")
x <- str_remove(x, "[:][0-9][0-9]$")如你所见:"0.9305555555555547“、"1520”、"1000“、"0.125”、"1525“
问题是小数需要乘以2400才能回到军事时间,但我也不想乘整数(因为它们已经在军事时间了)。
x本质上是数据文件中的一个变量。
我正在考虑使用if/ how逻辑,但我不知道如何实现它。
为了澄清,我想:
输入:"0.9305555555555547“、"15:20找到”、“上午10:00:00发现”、"0.125“、”找到15:25“
输出:"2233“、"1520”、"1000“、"0300”、"1525“
发布于 2022-02-12 06:39:55
我们应该扩展AM/PM指标的准则,使力量不会相互错过。接下来,在子集中,我们处理十进制时间,帝国时间,24小时时间,以及return结果。
milt <- function(x) {
u <- trimws(gsub('\\D*(\\d*\\W?[AP]?M?)\\D*', '\\1', x))
u[grep('\\.', u)] <- sprintf('%04d', round(as.double(u[grep('\\.', u)])*2400))
u[grep('[AP]M', u)] <- strftime(strptime(u[grep('[AP]M', u)], '%I:%M:%S %p'), '%H%M')
u[grep(':', u)] <- gsub(':', '', u[grep(':', u)] )
return(u)
}
milt(x)
# [1] "2233" "1520" "1000" "2200" "0300" "1525" "0000" "1020"数据:
x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found",
"10:00:00 PM Found", "0.125", "Found 1525", "0000", "10:20")发布于 2022-02-12 01:32:42
在对regexes进行预处理之后,可以在这里使用str_detect()实现if/ here逻辑。
x <- ifelse(str_detect(x, "\\."),
as.integer(as.numeric(x) * 2400),
as.integer(x)) %>%
sprintf("%04d", .)这将以字符形式返回所需的输出。
然后,您可以这样做,将其解析为POSIXct
x <- as.POSIXct(x,
format = "%H%M",
origin = "1970-01-01",
tz = "UTC")发布于 2022-02-12 01:40:02
我完全按照你的逻辑,得到了完全相同的结果。
conversion
的数字前面。
x <- c("0.9305555555555547", "15:20 Found", "10:00:00 AM Found", "0.125", "Found 1525")
x <- str_extract(x, "[0-9]+.+[0-9]|[0-9][0-9][:][0-9][0-9]")
x <- str_remove(x, "[:]")
x <- str_remove(x, "[:][0-9][0-9]$")
x <- as.numeric(x)
x <- as.character(ifelse(x<1,x*2400,x))
for(i in 1:length(x)){
ii <- stri_locate_first_regex(x[i],"\\.")[1]
if(!is.na(ii)){
x[i] <- str_sub(x[i],1,ii-1)
}
}
for(i in 1:length(x)){
while (nchar(x[i])<4) {
x[i] <- paste0("0",x[i])
}
}
x
[1] "2233" "1520" "1000" "0300" "1525"
>https://stackoverflow.com/questions/71087993
复制相似问题