これは前のquestionの回答に基づいています。データフレーム内の複数のカテゴリから共通の要素を見つけるか?
df
year code
2009 a
2009 a
2009 b
2010 b
2010 b
2011 b
2011 c
2011 c
df内のすべての年に共通のコードを選択します。ここでは "b"です。一つの解決策は次のとおりです。実際には
Reduce(intersect, list(unique(df$code[df$year==2009]),
unique(df$code[df$year==2010]),
unique(df$code[df$year==2011])))
、DFは約15年間、コード、数千、数百万行、および複数の列が含まれています。まず、すべての年が含まれている場合、上記のコマンドはかなり長くなります。さらに、それはメモリを消費し、遅いです。これを行うにはより高速で/より速いコードがありますか?その後、
lvls = list(y = unique(df$year), c = levels(df$code))
library(Matrix)
tab = sparseMatrix(i = match(df$year, lvls$y),
j = match(df$code, lvls$c),
x = TRUE,
dimnames = lvls)
tab
#3 x 3 sparse Matrix of class "lgCMatrix"
# c
#y a b c
# 2009 | | .
# 2010 . | .
# 2011 . | |
そして、::
'削減(交差、分割(DFの$コード、DF $を年)) ' –