参数不是数字或逻辑函数 rollapply,后跟由强制引入的 NA

Argument is not numeric or logical with function rollapply, followed by NAs introduced by coercion

我正在尝试计算基于 10 分钟数据的数据框中每 3 个观察值的平均值,我正在尝试将其平均化为半小时。我的数据如下所示:

    Date             Value
2017-09-20 09:19:59 96.510
2017-09-20 09:30:00 113.290
2017-09-20 09:40:00 128.370
2017-09-20 09:50:00 128.620
2017-09-20 10:00:00 94.080
2017-09-20 10:10:00 208.150
2017-09-20 10:20:00 178.820
2017-09-20 10:30:00 208.440
2017-09-20 10:40:00 285.490
2017-09-20 10:49:59 305.020

我首先尝试使用 zoo 包 library (zoo) 中的函数 rollapply 计算均值,方法如下:

means <- rollapply(df, by=3, 3, FUN=mean)

但是,我收到了 50 条警告:

In mean.default(data[posns], ...) : argument is not numeric or logical: returning NA

我检查了我的 classes,值(数字)和日期是一个因素。然后我尝试通过以下方式将日期(因子)转换为日期 class:

`df$Date <- as.Date(df, format = "%Y-%m-%d %H:%m:%s")` and

df$Date <- strptime(time,"%Y-%m-%d %H:%M:%S",tz="GMT") and still didn't work.

我也试过用聚合计算均值,但还是不行。

library(chron)
aggregate(chron(times=Date) ~ Value, data=df, FUN=mean)

我得到了:

Error in convert.times(times., fmt) : format h:m:s may be incorrect In addition: Warning message: In convert.times(times., fmt) : NAs introduced by coercion

此时此刻我很绝望,很抱歉在这里提问。也许我的数据有问题,因为它首先是一个 xlxs 文件,我将奇怪的 excel 时间转换为 R 中的日期,但仍然......我想知道,因为它是因为一些日期有 :59秒结束。如果有帮助,我还可以在线 post 我的全部数据。非常感谢!

主要问题是您试图将 rollapply 与数据框一起使用,而不是单个列或向量。如果我正确理解了您的目标,则应该执行以下操作:

library(dplyr)
library(zoo)

df %>%
  # compute rolling means with a window width of 3
  mutate(means = rollmeanr(Value, k = 3, fill = NA)) %>%
  # decrease the frequency in accordance with the window width
  filter(seq_len(nrow(df)) %% 3 == 0) # or alternatively, slice(seq(3, nrow(df), 3))

# # A tibble: 3 x 3
#   Date                Value means
#   <dttm>              <dbl> <dbl>
# 1 2017-09-20 09:40:00  128.  113.
# 2 2017-09-20 10:10:00  208.  144.
# 3 2017-09-20 10:40:00  285.  224.

数据:

df <- structure(list(Date = structure(c(1505917199, 1505917800, 1505918400, 
1505919000, 1505919600, 1505920200, 1505920800, 1505921400, 1505922000, 
1505922599), class = c("POSIXct", "POSIXt"), tzone = ""), Value = c(96.51, 
113.29, 128.37, 128.62, 94.08, 208.15, 178.82, 208.44, 285.49, 
305.02)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", 
"data.frame"))

问题中的代码将 df 转换为一个矩阵,该矩阵将其转换为字符矩阵,然后尝试对两列中的每一列进行滚动平均,这两列都是字符。

如果使用时间序列表示,事情会容易得多。数据框确实不是表示时间序列的理想选择,因为您一直在协调时间列和数据,而如果您将其表示为动物园对象,则所有这些都将自动处理。

首先将 df 转换为动物园系列,然后 运行 rollapplyr。可选择将其转换回数据框或将其保留为动物园对象。

library(zoo)

z <- read.zoo(df)
Value <- rollapplyr(z, 3, by = 3, mean)
# fortify.zoo(Value)

如果你想用竖线表示,试试这个:

library(magrittr)
library(zoo)

Value <- df %>% read.zoo %>% rollapplyr(3, by = 3, mean)

备注

使用的输入 df 以可重现的形式是:

df <-
structure(list(Date = structure(c(1505913599, 1505914200, 1505914800, 
1505915400, 1505916000, 1505916600, 1505917200, 1505917800, 1505918400, 
1505918999), class = c("POSIXct", "POSIXt"), tzone = ""), Value = c(96.51, 
113.29, 128.37, 128.62, 94.08, 208.15, 178.82, 208.44, 285.49, 
305.02)), class = "data.frame", row.names = c(NA, -10L))