2017-02-23 5 views
0

これは前の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 . | | 

そして、::

+3

'削減(交差、分割(DFの$コード、DF $を年)) ' –

答えて

2

別の考え方として、あなたの代わりに多くのペアごとの交差点の道を便利かつ効率的にすることができ、年間発生箇所の構造に仕事ができるが

colSums(tab) == nrow(tab) 
# a  b  c 
#FALSE TRUE FALSE 

または、この場合は、より良い:

colnames(tab)[diff([email protected]) == nrow(tab)] 
#[1] "b" 

"DF" です:

df = structure(list(year = c(2009L, 2009L, 2009L, 2010L, 2010L, 2011L, 
2011L, 2011L), code = structure(c(1L, 1L, 2L, 2L, 2L, 2L, 3L, 
3L), .Label = c("a", "b", "c"), class = "factor")), .Names = c("year", 
"code"), class = "data.frame", row.names = c(NA, -8L)) 
0

tidyverse機能を使用して、入力としてdft1をconsiderng、あなたが試すことができます:

dft1 %>% 
    unique() %>% 
    group_by(code) %>% 
    filter(n_distinct(year) == length(unique(dft1$year))) 

与える:

year code 
    <int> <chr> 
1 2009  b 
2 2010  b 
3 2011  b 
関連する問題