1
假設我們有一個這樣的數據幀:多維直方圖,其中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有直方圖:Multidimension histogram in python。 R中有類似的東西嗎?在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))
)
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'?你的函數似乎在返回所要求的內容:每一行都是一個向所有維度(中斷的組合)和該組合的數據發生次數的中斷矢量 – Dimon
另一件事是'table(res)'爆炸數據大小。有沒有辦法做到這一點,只爲非零計數?是的,你當然可以做'h <- h[h$Freq> 0'],但是由於'table(res)'的原因,它仍然會導致內存使用的高峯。 – Dimon
如果知道所期望的結果究竟是什麼,這可以得到改善。例如,我認爲融合功能可能是一種選擇,因此用「長度」來融化。您應該很容易調整功能,以便您可以手動提供休息時間。看一看'hist.default'的代碼,以獲得一個相當全面的方法。 – Roland