更快的子集数据方法 table 而不是 for 循环 R

Faster way to subset data table instead of a for loop R

我在 R 中有一个数据 table(您需要安装数据 table 包),它使用 X 和 Y 坐标以及来自正态分布和均匀分布的随机数据值生成。坐标表示 2000x1600 阵列上的点,必须分成 16 个较小的 "sectors",每个 500x400。这些部门需要采用正态分布值的平均值,除以均匀分布值的 min^2。我还使用提供的函数 startstop 创建了两个变量 x 和 y,它们具有 16 个扇区的坐标和一个计算每个扇区数字的函数。

library(data.table)
DT <- data.table(X = rep(1:2000, times = 1600), Y = rep(1:1600, each = 2000), Norm =rnorm(1600*2000), Unif = runif(1600*2000))

sectorCalc <- function(x,y,DT) {
    sector <- numeric(length = 16)
    for (i in 1:length(sector)) {
        sect <- DT[X %between% c(x[[1]][i],x[[2]][i]) & Y %between% c(y[[1]][i],y[[2]][i])]
        sector[i] <- sCalc(sect)
    }
    return(sector)
 }

startstop <- function(width, y = FALSE) {
    startend <- width - (width/4 - 1)
    start <- round(seq(0, startend, length.out = 4))
    stop <- round(seq(width/4, width, length.out = 4))
    if  (length(c(start,stop)[anyDuplicated(c(start,stop))]) != 0) {
        dup <- anyDuplicated(c(start,stop))
        stop[which(stop == c(start,stop)[dup])] <- stop[which(stop == c(start,stop)[dup])] - 1
}
    if (y == TRUE) {
        coord <- list(rep(start, each = 4), rep(stop, each = 4))
  } else if (y == FALSE) {
        coord <- list(rep(start, times = 4), rep(stop, times = 4))
  }
  return(coord)
}

x <- startstop(2000)
y <- startstop(1600, T)

sectorNos <- sectorCalc(x,y,DT)

startstop 函数并不是真正的问题,但我需要一种更快的方法来对数据进行子集化 table。必须对 'sectorCalc' 函数进行一些修改。 for 循环是我能想到的最好的方法,但我对数据 tables 没有太多经验。关于更快地分解数据的任何想法 table?

要替换您的 sectorCalc 函数,我认为我们可以使用 data.tables joins

当您遍历 sector 的每一行时,您只需创建一个 data.table 来加入您的 sector 数据, 指定要连接的列(这里我使用 key_col),并为每一行指定一个 'group' 变量,使我们能够执行 最后的计算:

x <- startstop(2000)
y <- startstop(1600, T)
## copy the original DT
dt <- copy(DT)


dt_xy <- data.table(x_1 = x[[1]],
                    x_2 = x[[2]],
                    y_1 = y[[1]],
                    y_2 = y[[2]])


dt[, key_col := 1]
dt_xy[, `:=`(key_col = 1, xy_grp = seq(1,.N))]

## Use a data.table join, allowing cartesian, then filter out results.
dt_res <- dt[ dt_xy, on="key_col", allow.cartesian=T][x_1 <= X & X <= x_2 & y_1 <= Y & Y <= y_2]

## calculate 'sect' as required.
dt_sect <- dt_res[, .(sect = mean(Norm)/min(Unif)^2)   , by=.(xy_grp)]

一个解决方案,不仅使用包 data.table,还使用 ​​cut 函数来构建区间 "groups":

# Create your test data
library(data.table)

set.seed(123)      # make random numbers reproducible to allow comparison of different answers
DT <- data.table(X = rep(1:2000, times = 1600), Y = rep(1:1600, each = 2000), Norm =rnorm(1600*2000), Unif = runif(1600*2000))

# calculate the sector by cutting the x and y values into groups defined by the interval breaks
DT[, x.sect := cut(DT[, X], c(0, 499, 1000, 1500, 2000), dig.lab=10)] # Intervals should be: seq(0, 2000, by=500) lower bound is less one since it is not included in the interval (see help for cut function)
DT[, y.sect := cut(DT[, Y], c(0, 399, 800, 1200, 1600), dig.lab=10)] # Intervals should be: seq(0, 1600, by=400)

# Now calculate per group (calculation logic "stolen" from the working answer of user "Symbolix"
DT[, .(sect = mean(Norm)/min(Unif)^2), by=.(x.sect, y.sect)]

请注意:我认为原始解决方案中第一个和第二个区间的大小是错误的(499 而不是 x 的 500 和 399 而不是 400 的 y 以便我无法使用 seq 函数来重现您想要的间隔,但必须手动枚举间隔中断)。

编辑 1: 我已将添加 x.sect 和 y.sect 列的原始代码替换为通过引用添加列的改进解决方案 (:=).

编辑 2: 如果您想对结果进行排序,您有(至少)两个选择:

# "Chaining" (output is input of next)
DT[, .(sect = mean(Norm)/min(Unif)^2), by=.(x.sect, y.sect)][order(x.sect, y.sect),]
# Or: Use the "keyby" param instead of "by"
DT[, .(sect = mean(Norm)/min(Unif)^2), keyby=.(x.sect, y.sect)]

编辑 3:将 dig.lab=10 参数添加到上面代码中的 cut 函数以避免间隔中断的科学记数法。