r - 当存在平局时,在因子变量中获取模式及其频率
问题描述
我正在寻找最常见的值(字符串)及其频率。
预期结果是一个包含三列的数据框:
char: the names of the original columns
mode: the most frequent value in each char
freq: the frequency of the modes
当频率相同时,我想将所有合格的值放在一个单元格中,用逗号分隔。——或者有更好的表现形式吗?
问题:我不知道如何处理领带。
我使用 table() 函数来获取每列的频率表。
clean <- read.xlsx("test.xlsx", sheet = "clean") %>% as_tibble()
freqtb <- apply(clean, 2, table)
这是我在freqtb中得到的第二张表:
$休12
个 休 天 饿
1 33 2 1
然后我遍历表格:
freq <- vector()
mode <- vector()
for (tb in freqtb) {
max = max(tb)
name = names(tb)[tb==max]
freq <- append(freq, max)
mode <- append(mode, name)
}
results <- data.frame(char = names(freqtb), freq = freq, mode=mode)
该模式比其他向量具有更大的长度,并且它不能附加到结果。我敢打赌这是由于关系。
这个“模式”变量如何获得相同的长度?
解决方案
您可以在此处对代码进行一些小的修改以获得Mode
功能。然后Map
将您的数据框和rbind
结果放在一起
options(stringsAsFactors = F)
set.seed(2)
df.in <-
data.frame(
a = sample(letters[1:3], 10, T),
b = sample(1:3, 10, T),
c = rep(1:2, 5))
Mode <- function(x) {
ux <- unique(x)
tab <- tabulate(match(x, ux))
ind <- which(tab == max(tab))
data.frame(char = ux[ind], freq = tab[ind])
}
do.call(rbind, lapply(df.in, Mode))
# char freq
# a c 4
# b 1 4
# c.1 1 5
# c.2 2 5
推荐阅读
- php - 选择查询中的 Laravel 传递列表参数(列)
- python-3.x - How to return string composed of superscript inside of fraction for matplotlib legend label?
- c - C 中哪些运算符的优先级错误?
- c# - 为什么我的 .net 核心 API 取消请求?
- r - 检查下载的 jpg 的矢量并找到丢失的 id
- c# - @Before 方法调用的用法
- firebase - 如何从 Cloud Firestore 获取 Flutter App 的简单数据?
- python - 如何使用多个保存的模型进行预测?
- r - 数据帧内和数据帧之间的数据帧操作
- java - JAR 库到 TomCat