如何计算每列的相同值计数(所有列值都是数字)小于 R 数据集中该列的 40%

How to calculate same value counts for each column (all columns values are numeric) is less than 40% of that column in a dataset in R

在 R 代码中,我想 select 数据集中每列出现相同值的所有变量小于该列的 40%。 我正在应用 sapply,但没有得到正确的输出。 注意:所有列值都是数字。

train = train[, sapply(train, function(col) length(unique(col))) < 0.4*nrow(train)]

请建议如何进行。

通过玩玩具数据集,我发现这段代码有效

train[, sapply(train, function(x) {(sort(table(x), decreasing = TRUE)/nrow(train))[[1]] < 0.4})]

基本上,我为 train 中的每个数字列创建相对频率的 table(按降序排列),然后我检查每个列的最频繁值是否小于40% 的次数。如果是,则选择该列,否则丢弃。