R语言 添加缺失数据xts并将其与0值匹配

xt0899hw  于 2023-04-09  发布在  其他
关注(0)|答案(2)|浏览(101)

我遇到了缺少数据的问题,有一些分钟值丢失,正如你在下面看到的...我使用as. POSIX ct将日期设置为索引。如何添加缺少的日期以获得完整的ts并将它们与0的“Num_tweets”匹配?
开始时间= 2012-12-01 12:52:00结束时间= 2012-12-01 13:02:00
我的数据看起来像这样:

Date, Num_tweets
2012-12-01 12:52:00, 3
2012-12-01 12:53:00, 3
2012-12-01 12:54:00, 1
2012-12-01 12:55:00, 2
2012-12-01 12:56:00, 3
2012-12-01 12:59:00, 3
2012-12-01 13:00:00, 2
2012-12-01 13:02:00, 1

我的期望:

Date, Num_tweets
2012-12-01 12:52:00, 3
2012-12-01 12:53:00, 3
2012-12-01 12:54:00, 1
2012-12-01 12:55:00, 2
2012-12-01 12:56:00, 3
2012-12-01 12:57:00, 0
2012-12-01 12:58:00, 0
2012-12-01 12:59:00, 3
2012-12-01 13:00:00, 2
2012-12-01 13:01:00, 0
2012-12-01 13:02:00, 1

我该怎么做?谢谢!

j5fpnvbx

j5fpnvbx1#

我们可以使用complete

library(dplyr)
library(tidyr)
df1  %>% 
 mutate(Date = as.POSIXct(Date)) %>%
 complete(Date = full_seq(Date, period = 60), fill = list(Num_tweets = 0))
  • 输出
# A tibble: 11 × 2
   Date                Num_tweets
   <dttm>                   <int>
 1 2012-12-01 12:52:00          3
 2 2012-12-01 12:53:00          3
 3 2012-12-01 12:54:00          1
 4 2012-12-01 12:55:00          2
 5 2012-12-01 12:56:00          3
 6 2012-12-01 12:57:00          0
 7 2012-12-01 12:58:00          0
 8 2012-12-01 12:59:00          3
 9 2012-12-01 13:00:00          2
10 2012-12-01 13:01:00          0
11 2012-12-01 13:02:00          1

数据

df1 <- structure(list(Date = c("2012-12-01 12:52:00", "2012-12-01 12:53:00", 
"2012-12-01 12:54:00", "2012-12-01 12:55:00", "2012-12-01 12:56:00", 
"2012-12-01 12:59:00", "2012-12-01 13:00:00", "2012-12-01 13:02:00"
), Num_tweets = c(3L, 3L, 1L, 2L, 3L, 3L, 2L, 1L)), class = "data.frame", 
row.names = c(NA, 
-8L))
kulphzqa

kulphzqa2#

可以通过将xts对象与具有所需索引值的零宽度xts对象合并来实现此目的。

library(xts)
# using df1 from akrun's answer
x <- xts(df1$Num_tweets, as.POSIXct(df1$Date))

one_min_seq <- xts(, seq(start(x), end(x), by = "1 min"))
y <- merge(Num_tweets = x, one_min_seq, fill = 0)
print(y)
##                     Num_tweets
## 2012-12-01 12:52:00          3
## 2012-12-01 12:53:00          3
## 2012-12-01 12:54:00          1
## 2012-12-01 12:55:00          2
## 2012-12-01 12:56:00          3
## 2012-12-01 12:57:00          0
## 2012-12-01 12:58:00          0
## 2012-12-01 12:59:00          3
## 2012-12-01 13:00:00          2
## 2012-12-01 13:01:00          0
## 2012-12-01 13:02:00          1

相关问题