R 运行平均值/SD:如何根据标准在平均值窗口内进行选择

R 运行平均值/SD:如何根据标准在平均值窗口内进行选择,r,moving-average,R,Moving Average,我需要计算移动窗口的移动平均值和标准偏差。使用catools包,这就足够简单了 。。。然而,我想做的是,在定义了移动窗口之后,我只想从窗口中的那些值中取一个平均值,这些值对应的其他变量的值符合某些标准。例如,我想计算移动平均温度,仅使用窗口内的值,例如+/-2天,当相对湿度高于80%时 有人能帮我指出正确的方向吗?以下是一些示例数据: da <- data.frame(matrix(c(12,15,12,13,8,20,18,19,20,80,79,91,92,70,94,80,80,90

我需要计算移动窗口的移动平均值和标准偏差。使用catools包,这就足够简单了

。。。然而,我想做的是,在定义了移动窗口之后,我只想从窗口中的那些值中取一个平均值,这些值对应的其他变量的值符合某些标准。例如,我想计算移动平均温度,仅使用窗口内的值,例如+/-2天,当相对湿度高于80%时

有人能帮我指出正确的方向吗?以下是一些示例数据:

da <- data.frame(matrix(c(12,15,12,13,8,20,18,19,20,80,79,91,92,70,94,80,80,90), 
               ncol = 2, byrow = TRUE))

names(da) = c("Temp", "RH") 
谢谢

Brad

我没有使用catools,但在该软件包中最相关函数的帮助文本中,您可以看到x,输入数据,可以是数字向量[…]或具有n行的矩阵。在您的情况下,矩阵替代方案是最相关的-您希望计算焦点变量Temp的平均值,以第二个变量RH为条件,函数需要访问这两个变量。但是,[i]f x是一个矩阵,因此每列将单独处理。因此,我认为catools无法解决您的问题。相反,我建议你申请动物园套餐。在rollapply中,参数为by.column。默认值为TRUE:如果为TRUE,则FUN将分别应用于每个列。但是,如上所述,我们需要访问函数中的两列,并将by.column设置为FALSE


欢迎来到SO!请添加一个,并请向我们展示。这样你就更有可能得到一个快速、有用的答案。干杯,谢谢你,亨里克!这是一个数据表,我想让我的移动窗口大小为3步da=data。framematrixc12,15,12,13,8,20,18,19,20,80,79,91,92,70,94,80,80,90,ncol=2,byrow=TRUE-namesda=cTemp,右键单击问题下方的“编辑”,并将其作为问题的一部分,不是在评论中。谢谢你的例子!您可能还希望了解如何在问题、答案和注释中以良好的方式格式化代码。谢谢您的回答!很抱歉延迟回复
# First, specify a function to apply to each window: mean of Temp where RH > 80
meanfun <- function(x) mean(x[(x[ , "RH"] > 80), "Temp"])

# Apply the function to windows of size 3 in your data 'da'.
meanTemp <- rollapply(data = da, width = 3, FUN = meanfun, by.column = FALSE)
meanTemp

# If you want to add the means to 'da', 
# you need to make it the same length as number of rows in 'da'.
# This can be acheived by the `fill` argument,
# where we can pad the resulting vector of running means with NA
meanTemp <- rollapply(data = da, width = 3, FUN = meanfun, by.column = FALSE, fill = NA)

# Add the vector of means to the data frame
da2 <- cbind(da, meanTemp)
da2

# even smaller example to make it easier to see how the function works
da <- data.frame(Temp = 1:9, RH = rep(c(80, 81, 80), each = 3))
meanTemp <- rollapply(data = da, width = 3, FUN = meanfun, by.column = FALSE, fill = NA)
da2 <- cbind(da, meanTemp)
da2

#     Temp RH meanTemp
# 1    1 80       NA
# 2    2 80      NaN
# 3    3 80      4.0
# 4    4 81      4.5
# 5    5 81      5.0
# 6    6 81      5.5
# 7    7 80      6.0
# 8    8 80      NaN
# 9    9 80       NA