我正在尝试t.test
使用来自两个单独列(sample1 和 sample2)的样本运行 7 天滚动窗口的两个样本 t 检验。从第一天开始,我想为每个测试获取 p 值并将它们添加到我当前的数据中。我尝试rollapply
了几种形式,但都没有成功。
# Stackoverflow question
library(data.table)
library(zoo)
# Create some Data
start = as.Date("2014-01-01")
end = as.Date("2014-12-31")
dat <- data.table(date = seq(start, end, by = "1 day"),
sample1 = sample(1:20, 365, replace = TRUE),
sample2 = sample(1:30, 365, replace = TRUE))
# Use rollapply with FUN = t.test
dat[, pvalue := rollapply(c(sample1, sample2), 7, FUN=t.test, alternative="less", conf.level=0.95, by.column = FALSE, partial = T, fill=NA, align='left')$p.value]
我收到以下错误:
# Error in t.test.default(data[replace(posns, !ix, 0)], ...) :
# not enough 'x' observations
第二次尝试:
# Use rollaply with more specific FUN
dat[, pvalue := rollapply(dat, width = 7,
FUN = function(df) t.test(x=sample1, y=sample2, data = as.data.frame(df), alternative="less", conf.level=0.95)$p.value,
by.column = FALSE, partial = T, fill=NA, align='left')]
仅创建一个测试并重复值。
第三次尝试:
# Tried to create vector using rollapply
r <- rollapply(dat, width = 7,
FUN = function(df) with(df, t.test(x=sample1, y=sample2)$p.value))
我收到以下错误:
# Error in eval(substitute(expr), data, enclos = parent.frame()) :
# invalid 'envir' argument of type 'character'
# Called from: eval(substitute(expr), data, enclos = parent.frame())