首页 文章

带R的多维直方图

提问于
浏览
1

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

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)

1 回答

  • 1

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

    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)
    

相关问题