多维直方图与 R

Multidimensional Histogram with R

假设我们有这样一个数据框:

dat <- data.frame(
    a = rnorm(1000),
    b = 1/(rnorm(1000))^2,
    c = 1/rnorm(1000),
    d = as.factor(sample(c(0, 1, 2), 1000, replace=TRUE)),
    e = as.factor(sample(c('X', 'Y'), 1000, replace=TRUE))
)

我们想计算此数据在所有维度(即 a、b、c、d、e)中的直方图,并在每个维度中指定间隔。显然,因子维度已经暗示了它们的中断。最终数据应该像 data.frame 一样,其中每一行都是跨所有维度的中断向量(中断组合)和该组合的数据出现次数。 Python numpy 有 histogramdd:Multidimension histogram in python。 R中有类似的东西吗?在 R 中执行此操作的最佳方法是什么?谢谢。

我最终使用了以下内容,其中 bin 计数作为最后一行传递给函数:

dat <- data.frame(
    a = rnorm(1000),
    b = 1/(rnorm(1000))^2,
    c = 1/rnorm(1000),
    d = as.factor(sample(c(0, 1, 2), 1000, replace=TRUE)),
    e = as.factor(sample(c('X', 'Y'), 1000, replace=TRUE))
)

dat[nrow(dat)+1,] <- c(10,10,10,NaN,NaN)

histnd <- function(df) {
  res <- lapply(df, function(x) {
    bin_idx <- length(x)
    if (is.factor(x) || is.character(x)) {
      return(x[-bin_idx])
    }
    #
    x_min <- min(x[-bin_idx])
    x_max <- max(x[-bin_idx])
    breaks <- seq(x_min, x_max, (x_max - x_min)/x[bin_idx])
    cut(x[-bin_idx], breaks)
    })
  res <- do.call(data.frame, res)
  res$FR <- as.numeric(0)
  res <- aggregate(FR ~ ., res, length)
}

h <- histnd(dat)

我不知道预期的结果是什么,但这应该提供了一个起点:

histnd <- function(DF) {
  res <- lapply(DF, function(x) {
    if (is.factor(x) || is.character(x)) return(x)
    breaks <- pretty(range(x), n = nclass.Sturges(x), min.n = 1)
    cut(x, breaks)
    })
  res <- do.call(data.frame, res)
  as.data.frame(table(res))
}

h <- histnd(dat)