滚动到data.table行上,并在函数中进行子集计算 [英] Rollapply over data.table rows with subset calculations in function

查看:62
本文介绍了滚动到data.table行上,并在函数中进行子集计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在data.table上应用一个函数。并且在函数中,我想使用data.table子集,以便下面的示例起作用。

I want to rollapply a function on a data.table. And in the function I would like to work with the data.table subset, so that the example below works.

library(zoo)
library(data.table)

dt <- data.table(i = 1:100,
                       x = sample(1:10, 100, replace = T),
                       y = sample(1:10, 100, replace = T))

rollapply(dt, width=10, FUN = function(dt_slice) dt_slice[, mean(x == y)])


推荐答案

您可以使用 rollapply sapply / 外部,以获得索引矩阵,然后<

You can use rollapply, or sapply/outer, to get a matrix of indices and then apply over that matrix with the operation you want

inds <- rollapply(seq_len(nrow(dt)), width = 10, FUN = I)
# or inds <- t(sapply(seq_len(1 + nrow(dt) - 10) - 1, `+`, 1:10))
# or inds <- outer(seq_len(1 + nrow(dt) - 10) - 1, 1:10, `+`)
# or inds <- embed(1:100, 10)[, 10:1] # thanks @Frank
apply(inds, 1, function(i) dt[i, mean(x == y)])

#  [1] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0
# [20] 0.0 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.2 0.2 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1
# [39] 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.1 0.1 0.1 0.1 0.1
# [58] 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.0 0.0 0.0 0.0
# [77] 0.1 0.1 0.1 0.2 0.2 0.2 0.2 0.2 0.2 0.2 0.1 0.1 0.1 0.0 0.0

尽管如果操作如此简单,您也可以这样做

Although if the operation is as simple as this example you can also do

dt[, rollapply(x == y, width = 10, FUN = mean)]

这篇关于滚动到data.table行上,并在函数中进行子集计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆