我没有使用过catools
,但是在该包中(可能)最相关函数的帮助文本中?runmean
,您看到x
,输入数据可以是“数字向量 [...] 或具有 n 行的矩阵” . 在您的情况下,矩阵替代最相关 - 您希望计算焦点变量 Temp 的平均值,以第二个变量 RH 为条件,并且该函数需要访问这两个变量。但是,“[i]fx 是一个矩阵,每一列都将单独处理”。因此,我认为catools
不能解决您的问题。相反,我会建议rollapply
在zoo
包装中。在rollapply
,你有论据by.column
。默认为TRUE
:“如果为真,则将 FUN 分别应用于每一列”。但是,如上所述,我们需要访问函数中的两列,并设置by.column
为FALSE
.
# 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