首页 > 解决方案 > 当存在平局时,在因子变量中获取模式及其频率

问题描述

我正在寻找最常见的值(字符串)及其频率。

预期结果是一个包含三列的数据框:

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)

该模式比其他向量具有更大的长度,并且它不能附加到结果。我敢打赌这是由于关系。

这个“模式”变量如何获得相同的长度?

标签: r

解决方案


您可以在此处对代码进行一些小的修改以获得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

推荐阅读