3

私はデータフレームの変換に取り組んでおり、以前の投稿で Arun と Ricardo に取り組んでいました。

前の投稿

Arun は、私がやろうとしていたことを達成するための素晴らしい解決策 (行列乗算) を提案しました。

そのソリューションは、例で述べたような小さなデータ セットで機能しました。現在、次のサイズのデータ​​ フレームで同じソリューションを実行しています。

Total rows: 143345
Total Persons: 98461
Total Items :  30

さて、次のコマンドを実行すると

 A <- acast(Person~Item+BorS,data=df,fun.aggregate=length,drop=FALSE)

このエラーが発生します..

Error: segfault from C stack overflow

これは、十分な処理/メモリ能力がないためです。私のマシンには 4 GB RAM、2.8 GHz i7 プロセッサ (Macbook) が搭載されていますか? この種のケースをどのように処理しますか?

4

1 に答える 1

4

data.table解決策。これは、最初に集計してから、新しい data.table を作成し、参照によって入力することで機能します

library(data.table)

# some sample data
DT <- data.table(Person = sample(98461, 144000, replace = TRUE), item = sample(c(letters,LETTERS[1:4]), 144000, replace = TRUE), BorS = sample(c('B','S'), 144000, replace = TRUE))
# aggregate to get the number of rows in each subgroup by list item and BorS 
# the `length` of each subgroup
DTl <- DT[,.N , by = list(Person, item, BorS)]
# the columns you want to create
newn <- sort(DT[, do.call(paste0,do.call(expand.grid,list(unique(item),unique(BorS) )))])
# create a column which has this id combination in DTl
DTl[, comnb := paste0(item, BorS)]
# set the key so we can join / subset easily
setkey(DTl, comnb)
# create a data.table that has 1 row for each person, and has  columns for all the combinations
# of item and BorS
DTb <- DTl[, list(Person)][, c(newn) := 0L]
# set the key so we can join / subset easily
setkey(DTb, Person)
# this bit could be far quicker, but I think
# would require a feature request to data.table
for(nn in newn){
  # for each of the cominations extract which persons have
  # this combination >0
  pp <- DTl[list(nn), list(Person,N)]
  # for the people who have N > 0
  # assign the correct numbers in the correct column in DTb
  DTb[list(pp[['Person']]), c(nn) := pp[['N']]]
}

最初の問題を完了するために、適切な列をDTbマトリックスとして抽出できます

A <- DTb[,-1,with = FALSE]

results <- crossprod(A)
于 2013-03-15T02:46:47.653 に答える