r - 每列出现频率最高的元素

标签 r matrix stata

我有以下矩阵:

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 是变量名。

最佳答案

它可以像这样在 base 中完成:

 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/

相关文章:

r - 如何有条件地选择/过滤R中每个组中的值

python - 如何在Python中编写numpy矩阵的函数

matlab - 在matlab中从矩阵绘制网络或图形

c++ - 对称矩阵中的线性索引

loops - 在 Stata 中附加本地宏

r - 将数据帧中的值与另一个数据帧中的值进行匹配,并用另一个数据帧中的相应模式替换前一个

r - 在 R 中,为什么我会在 POSIXct 和 POSIXlt 之间获得一毫秒的差异?

python - Pandas 由长到宽的 reshape ,通过两个变量

javascript - 无法让 Leaflet.Spin 插件在 R Shiny 中工作

r - lme4::glmer 与 Stata 的 melogit 命令