有没有一种方法可以将R中不均匀间隔的数据帧生成时间序列?
我有一个带有成对值的数据集,我已将其转换为如下数据帧:有没有一种方法可以将R中不均匀间隔的数据帧生成时间序列?,r,dataframe,time-series,R,Dataframe,Time Series,我有一个带有成对值的数据集,我已将其转换为如下数据帧: (50.0, 0.0), (49, 27.891), (48, 28.119), (47, 28.146), (46, 28.158), (45, 28.195), (44, 28.261), (43, 28.274), (42, 28.316), (41, 28.326), (40, 28.608), (39, 28.687), (38, 28.736), (37, 28.746) numeric_data clean_t
(50.0, 0.0), (49, 27.891), (48, 28.119),
(47, 28.146), (46, 28.158), (45, 28.195),
(44, 28.261), (43, 28.274), (42, 28.316),
(41, 28.326), (40, 28.608), (39, 28.687),
(38, 28.736), (37, 28.746)
numeric_data
clean_time_numeric clean_position_numeric
1 0.000 50
2 27.891 49
3 28.119 48
4 28.146 47
5 28.158 46
此数据帧具有时间点和滑块在该时间点的位置。我想做一个时间序列,间隔为0.001,滑块的相应位置在下一列中,因此位置将是50,直到27891行
我在另一篇文章中看到的xts
和zoo
软件包中尝试了这段代码:
df1.zoo <- zoo(clean_time_numeric)
df2 <- as.data.frame(as.zoo(merge(as.xts(df1.zoo), as.xts(zoo(,seq(start(df1.zoo[1]),end(df1.zoo[89]), order.by = as.POSIXct.numeric(clean_time_numeric, tryformats = "%Y%m%d%H%M%S")))))))
我是新的编码在R,所以我真的不知道如何处理这个问题,或者如果有一个更简单的方法来解决这个问题,任何建议都欢迎
谢谢,
编辑:我也试过这个:
numeric_data$clean_time_numeric<- as.POSIXct.numeric(numeric_data$clean_time_numeric, tz= "GMT", origin = "1970-01-01", tryformats = "%H:%M:%S")
tseries <- data.frame(x = seq(head(numeric_data$clean_time_numeric,1),tail(numeric_data$clean_time_numeric,1),by = "sec"))
res <-merge(tseries, numeric_data, by.x="x",by.y="clean_time_numeric",all.x = TRUE)
xts(res$clean_position_numeric,order.by = res$x)
numeric\u data$clean\u time\u numeric可能的解决方案:
创建一个间隔为0.001的序列
将此序列连接到原始数据帧
使用zoo::na.locf
将na替换为最后一个已知值
df使用注释末尾重复显示的numeric_data
数据框,使用read.zoo
将其转换为zoo系列。然后将其频率设置为1000(这是每单位间隔的点数),转换为ts类,并使用na.locf0
(或na.approx
用于线性插值或na.spline
用于样条插值)填充通过从zoo到ts的转换创建的NAs
library(zoo)
z <- read.zoo(numeric_data)
frequency(z) <- 1000
tt <- na.locf0(as.ts(z))
length(tt)
## [1] 28159
deltat(tt)
## [1] 0.001
range(time(tt))
## [1] 0.000 28.158
df <- read.table(text = "
clean_time_numeric clean_position_numeric
0.000 50
27.891 49
28.119 48
28.146 47
28.158 46",header=T)
time.001 <- data.frame(time = seq(min(df$clean_time_numeric), max(df$clean_time_numeric), by =0.001))
library(dplyr)
df.001 <- dplyr::full_join(df, time.001, by = c("clean_time_numeric"="time")) %>%
arrange(clean_time_numeric) %>%
mutate(clean_position_numeric = zoo::na.locf(clean_position_numeric))
head(df.001)
clean_time_numeric clean_position_numeric
1 0.000 50
2 0.001 50
3 0.002 50
4 0.003 50
5 0.004 50
6 0.005 50
tail(df.001)
clean_time_numeric clean_position_numeric
28155 28.153 47
28156 28.154 47
28157 28.155 47
28158 28.156 47
28159 28.157 47
28160 28.158 46
library(zoo)
z <- read.zoo(numeric_data)
frequency(z) <- 1000
tt <- na.locf0(as.ts(z))
length(tt)
## [1] 28159
deltat(tt)
## [1] 0.001
range(time(tt))
## [1] 0.000 28.158
numeric_data <-
structure(list(clean_time_numeric = c(0, 27.891, 28.119, 28.146,
28.158), clean_position_numeric = 50:46), class = "data.frame", row.names = c(NA, -5L))