為了將寬資料改造成長資料,我通常發現 data.table 包中的melt.data.table 是記憶體效率最高的方法。在記憶體方面,這dplyr與base在線的和軟體包相比毫不遜色。但是,我發現自己無法融化大約 11GB 大小的物件,并回傳以下訊息:
Error: cannot allocate vector of size 10.5 Gb
我的 Windows 計算機有 32GB RAM,使用 64 位 R。我的melt命令與資料集的 5 行版本包含在下面(有效)。實際資料有近2億行。
library(data.table)
test <- structure(list(time = structure(c(667150201.25, 667153801.25, 667157401.25, 667161001.25, 667164601.25), tzone = "UTC", class = c("POSIXct", "POSIXt")),
red = c(-2.25, -2.375, -2.5, -0.5, -1.625),
orange = c(1.625, 1.375, 1.625, 2.25, 2.5),
yellow = c(1.25, 0.5, 1.5, 1.5, 1.625),
green = c(2.875, 2.625, 2.5, 3.25, 3),
blue = c(4.75, 4.5, 4.75, 4.75, 5.125),
purple = c(0.125, -0.125, 0.5, 1.25, 1.375),
violet = c(3.125, 2.875, 3.125, 3.375, 3.375),
pink = c(3.75, 1.75, 1.5, 1, 0.5)),
row.names = c(NA, -5L), class = c("data.table","data.frame"))
melt(test, id.vars='time',
measure.vars=c('red','orange','yellow','green','blue','purple','violet','pink'),
variable.name='color', value.name="value")
是否有更高效的方法將資料形式寬轉換為長?目標是擁有一個包含 3 列的資料集:時間、顏色和值。
uj5u.com熱心網友回復:
也許這樣的方法可行?我不知道如何衡量實際的記憶體使用..
library(data.table)
test.split <- split.default(test[, -1], names(test)[-1], )
data.table::rbindlist(lapply(test.split, cbind, test$time), use.names = FALSE, id = "color")
uj5u.com熱心網友回復:
如果記憶體是問題,那么采取較小的步驟應該可以解決它:
mv <- c('red','orange','yellow','green','blue','purple','violet','pink')
OUT <- data.table(color = character(0L), value = numeric(0L))
for (m in mv) {
OUT <- rbind(OUT, test[, .(color = m, value = get(m))])
set(test, j = m, value = NULL) # Delete the data since it is not necessary anymore
}
OUT[, time := rep(test$time, .N/nrow(test))]
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/343672.html
