我有以下矩阵:

set.seed(3690)

example = matrix(sample(1:10, 100, replace = TRUE), nrow = 10)

      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    4    4    2    7    2    2    3    8    2     5
 [2,]    7    3    2    6    6    5    7    8    1     3
 [3,]    7    5    7    9    4    9    4    8    2     7
 [4,]    5    3    4    2    1    5    9   10    9     5
 [5,]    9   10    7    2    7    4    9    1    1     9
 [6,]    2    3    5    1    2    8    1    5    9     4
 [7,]    5    4   10    5    9   10    1    6    1    10
 [8,]    6    3    9    7    1    1    9    2    1     7
 [9,]    5    9    4    8    9    9    5   10    5     4
[10,]   10    1    4    7    3    2    3    5    4     5


如何在R中找到每列中最频繁出现的10(或最高5)元素?

这就是我在Stata中编码的方式:

tempvar freq
generate byte `freq'=1

sort serial t0400_0415_d1-t0345_0400_d7

collapse (count) `freq' serial,  by(t0400_0415_d1-t0345_0400_d7)
list, sepby(`freq')

gsort -`freq' t0400_0415_d1-t0345_0400_d7
generate rank=_n
keep if rank<=20
drop `freq'

sort  t0400_0415_d1-t0345_0400_d7
tempfile top20
save `"`top20'"'

sort rank t0400_0415_d1-t0345_0400_d7
list rank t0400_0415_d1-t0345_0400_d7


请注意,t0400_0415_d1-t0345_0400_d7是变量名。

最佳答案

可以在这样的基础上完成:

 sapply(1:ncol(example), function(x) rev(tail(names(sort(table(example[,x]))), 2)))


如果您想知道频率,请忽略names()

sapply(1:ncol(example), function(x) rev(tail(sort(table(example[,x])), 2)))

关于r - 每列最频繁的元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55878025/

10-12 17:09
查看更多