2016-03-15 12 views
5

私はこの行列を持っていますmymatcol1の各項目の番号を取得するにはtable((mymat[,"col1"])を行うことができます。しかし、col2に一意の値がある場合にのみ、カウントが必要です。以下mymatのために、私はこの結果をしたい:列内の一意の値のテーブル数を取得する方法

app gg chh 
1 2 1 

mymat

col1 col2 
app d 
app d 
gg  e 
gg  f 
gg  e 
chh f 
chh f 
chh f 

答えて

8

あなたは、データをサブセット化uniqueを使用(matrixdata.frameのために働く)、その後、tableを呼び出すことができます。

table(unique(mymat)[,1])

これは、これは(表に非ゼロをカウントしている

# app chh gg 
# 1 1 2 
+1

非常に簡潔な答えを。私は 'base :: unique'に' data.frame'メソッドがあるのを忘れていました –

7

あなたは、データをサブセットし、その後tableを呼び出すためにduplicatedを使用することができます。

table(subset(df, !duplicated(paste(col1, col2)), select = col1)) 
#app chh gg 
# 1 1 2 

第二の選択肢として、ここにありますdplyrアプローチ:

library(dplyr) 
distinct(df) %>% count(col1) # or distinct(df, col1, col2) if you have other columns 
#Source: local data frame [3 x 2] 
# 
# col1  n 
# (fctr) (int) 
#1 app  1 
#2 chh  1 
#3  gg  2 
1

を返します) -result

rowSums(table(df$col1, df$col2)!=0) 

結果:使用

app chh gg 
    1 1 2 

データ:

df <- read.table(header=TRUE, text= 
"col1 col2 
app d 
app d 
gg  e 
gg  f 
gg  e 
chh f 
chh f 
chh f") 
0

他の提案は優れているが、ここで私は多様性のための別の可能性投げる:

apply(dcast(df, col1 ~ col2)[-1], 1, function(x) {sum(x > 0)}) 
関連する問題