在data.table中使用rollapply测试两个变量

时间:2016-03-31 03:31:17

标签: r data.table rollapply

我尝试使用7天滚动窗口运行两个样本t检验rollapply,样本来自两个单独的列(sample1和sample2)。我希望获得每个测试的p值,并将它们添加到我当前的数据中,从第1天开始。我已经尝试了几种形式的# 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())

我收到以下错误:

{{1}}

0 个答案:

没有答案