2017-01-28 9 views
1

私は100回の観測(A、B、C、Dのいずれでもよい)を持つオブジェクトを持っており、各グループの回数(A、B、C、D)このオブジェクトに表示されます:観測の出現回数をカウントする

例:

A<-rnorm(100, mean = 0, sd = 1) 
B<-rnorm(100, mean = 0, sd = 1) 
C<-rnorm(100, mean = 0, sd = 1) 
D<-rnorm(100, mean = 0, sd = 1) 

the.matrix<-matrix(c(A,B,C,D),ncol=4) 
colnames(the.matrix)=c("As","Bs","Cs","Ds") 

rep<-100 
aux<-NULL 

for (i in 1:rep) { 
    aux[i]<-ifelse(max(the.matrix[i,])==the.matrix[i,1],"A", 
      ifelse(max(the.matrix[i,])==the.matrix[i,2],"B", 
      ifelse(max(the.matrix[i,])==the.matrix[i,3],"C", 
      ifelse(max(the.matrix[i,])==the.matrix[i,4],"D", "error")))) 
} # if you found a simplest way to collect this information, please share this here 

は今AUX A、B、CおよびDの異なる量の100回の観測を持っている私は、各文字がループすることなく、AUX

答えて

1

別のオプションに表示された回数を知る必要がありますにmax.colです列のインデックスを取得し、その後、列名を置き換えるためにそれを使用して、我々はOPのコード

に基づいて table

table(colnames(the.matrix)[max.col(the.matrix)]) 
# As Bs Cs Ds 
# 34 20 15 31 

頻度を取得

table(aux) 
# aux 
# A B C D 
# 34 20 15 31 

注:seedは乱数生成用に設定されていません。

関連する問題