【发布时间】:2015-09-16 17:11:30
【问题描述】:
假设我们有一个这样的数据框:
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)
【问题讨论】:
标签: r histogram multi-dimensional-scaling