我有傳感器資料,想創建缺失的時間戳并插入特征值。目前我有測量它們之間不同的持續時間。我想要更高的金額。下面是一個簡化的 df
df1 = data.frame (
value =c('5','15','10','10','5','15'),
time = as.POSIXct(c('2018-06-03 19:40:00','2018-06-03 19:42:00','2018-06-03 19:43:00','2018-06-03 19:45:00','2018-06-03 19:46:00','2018-06-03 19:48:00')))
如果我使用 padr 包這樣做,它會起作用。
df2=df1 %>% pad(start_val = df1$time[1], end_val = df1$time[6],interval = "sec")
df2$value <- na.approx(df2$value)
但我想每 0.1 或 0.2 秒創建一個時間戳。padr 包可以處理 2 秒,但是當我收到此訊息時,似乎不到 1 秒不起作用
Error: The specified interval is invalid for the datetime variable. Not all original observation are in the padding. If you want to pad at this interval, aggregate the data first with thicken.
是否有可能以小于 1 秒的間隔創建時間戳?我試過這個
seq.POSIXt(as.POSIXct(df1$time[1]), as.POSIXct(df1$time[6]), units = "seconds", by = .2)
但它只創建一個時間戳向量
uj5u.com熱心網友回復:
我不熟悉padr,但最后一次呼叫應該給你一個亞秒級差異的序列,它可能不會被列印出來。部分亞秒精度在?DateTimeClasses解釋:
類“POSIXct”和“POSIXlt”能夠表示幾分之一秒。(兩種形式之間的分數轉換可能不準確,但精度會高于微秒級。)
僅當設定了 options("digits.secs") 時才會列印小數秒:請參閱 strftime。
因此,
options("digits.secs"=TRUE)
st <- Sys.time()
st.s <- seq(st, st 1, 0.1)
diff(st.s)
# Time differences in secs
# [1] 0.099999905 0.100000143 0.099999905 0.100000143 0.099999905 0.099999905
# [7] 0.100000143 0.099999905 0.100000143 0.099999905
st
# [1] "2021-12-29 20:00:33.0 CET"
dput(st)
# structure(1640804433.02173, class = c("POSIXct", "POSIXt"))
options("digits.secs"=FALSE)
st
# [1] "2021-12-29 20:00:33 CET"
dput(st)
# structure(1640804433.02173, class = c("POSIXct", "POSIXt"))
相同的資料,只是列印更準確。
uj5u.com熱心網友回復:
如果您想使用 .1 或 .2,并保留日期結構和內插值,這是可行的(請注意,您可以在 seq 呼叫中更改 .1 或 .2)。
library(tidyverse)
library(padr)
library(zoo)
df1 = data.frame (
value =c('5','15','10','10','5','15'),
time = as.POSIXct(c('2018-06-03 19:40:00','2018-06-03 19:42:00',
'2018-06-03 19:43:00','2018-06-03 19:45:00',
'2018-06-03 19:46:00','2018-06-03 19:48:00')))
# format decimal seconds so that it can be used to compare to the new date range
df1$time <- format(df1$time, "%Y-%m-%d %H:%M:%OS2")
# create the interval
y = seq.POSIXt(as.POSIXct(df1$time[1]), as.POSIXct(df1$time[6]), units = "seconds", by = .2)
# set up new data frame for original values and interpolation
dy = data.frame(time = y,
value = NA) %>%
mutate(time = format(y, "%Y-%m-%d %H:%M:%OS2"))
# obtain row numbers of those that already have values
wh <- sapply(df1$time, function(x) which(dy$time == x))
# return the original values to the dataset
dy[wh, ]$value <- unlist(df1$value)
# interpolate
dy$value <- na.approx(dy$value)
# take a look
head(dy)
# time value
# 1 2018-06-03 19:40:00.00 5.000000
# 2 2018-06-03 19:40:00.20 5.016667
# 3 2018-06-03 19:40:00.40 5.033333
# 4 2018-06-03 19:40:00.59 5.050000
# 5 2018-06-03 19:40:00.79 5.066667
# 6 2018-06-03 19:40:01.00 5.083333
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/397026.html
上一篇:檢查選擇列是否具有相同的值
