簡體   English   中英

大數據幀的高效組合和操作

[英]Efficient Combination and Operating on Large Data Frames

我在 R 中有 2 個相對較大的數據框。我正在嘗試盡可能高效地合並/查找所有組合。 結果 df 變得很大(長度為dim(myDF1)[1]*dim(myDF2)[1] ),因此我嘗試使用ff實施解決方案。 我也願意使用其他解決方案,例如bigmemory包來解決這些內存問題。 我幾乎沒有使用這些軟件包的經驗。

工作示例 - 假設我正在使用一些看起來類似於 USArrests 的數據框:

library('ff')
library('ffbase')


myNames <- USArrests

myNames$States <- rownames(myNames)
rownames(myNames) <- NULL

現在,我將制造2個的數據幀,其表示從myNames一些特定觀測的。 稍后我將嘗試通過行名來引用它們。

myDF1 <- as.ffdf(as.data.frame(matrix(as.integer(rownames(myNames))[floor(runif(3*1e5, 1, 50))], ncol = 3)))
myDF2 <- as.ffdf(as.data.frame(matrix(as.integer(rownames(myNames))[floor(runif(2*1e5, 1, 50))], ncol = 2)))


# unique combos:
myDF1 <- unique(myDF1)
myDF2 <- unique(myDF2)

例如,我在 myDF1 中的第一組狀態是myNames[unlist(myDF1[1, ]), ] 然后我將使用ikey找到 myDF1 和 myDF2 的所有組合:

# create keys:
myDF1$key <- ikey(myDF1)
myDF2$key <- ikey(myDF2)

startTime <- Sys.time()


# Create some huge vectors:
myVector1 <- ffrep.int(myDF1$key, dim(myDF2)[1])
myVector2 <- ffrep.int(myDF2$key, dim(myDF1)[1])


# This takes about 25 seconds on my machine:
print(Sys.time() - startTime)


# Sort one DF (to later combine with the other):
myVector2  <- ffsorted(myVector2)

# Sorting takes an additional 2.5 minutes:
print(Sys.time() - startTime)

1)有沒有更快的方法來排序?

# finally, find all combinations:
myDF <- as.ffdf(myVector1, myVector2)

# Very fast:
print(Sys.time() - startTime)

2)有沒有替代這種類型的組合(不使用RAM)?

最后,我希望能夠按行/列引用任何原始數據。 具體來說,我想獲得不同類型的 rowSums。 例如:

# Here are the row numbers (from myNames) for the top 6 sets of States:
this <- cbind(myDF1[myDF[1:6,1], -4], myDF2[myDF[1:6,2], -3])
this

# Then, the original data for the first set of States is:
myNames[unlist(this[1,]),]

# Suppose I want to get the sum of the Urban Population for every row, such as the first:
sum(myNames[unlist(this[1,]),]$UrbanPop)

3)最終,我想要一個具有上述 rowSum 的向量,這樣我就可以在myDF上執行某種類型的子集。 關於如何最有效地實現這一目標的任何建議?

謝謝!

我不太清楚您打算對 rowSum 和 3) 元素做什么,但是如果您想要 2 個 ff 向量的高效且對 RAM 友好的組合,要獲得所有組合,您可以使用 ffbase 中的 expand.ffgrid。 以下將在幾秒鍾內生成尺寸為 160Mio 行 x 2 列的 ffdf。

require(ffbase)
x <- expand.ffgrid(myDF1$key, myDF2$key)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM