我有一个有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
现在辅助有100个不同数量的A,B,C和D的观察结果。我只需要知道每个字母出现在aux中的次数
答案 0 :(得分:1)
没有循环的另一个选项是max.col
来获取列的索引,然后使用它来替换列名称,我们得到频率为table
table(colnames(the.matrix)[max.col(the.matrix)])
# As Bs Cs Ds
# 34 20 15 31
基于OP的代码
table(aux)
# aux
# A B C D
# 34 20 15 31
注意:未为随机数生成设置seed
。