【问题标题】:get the value of the most frequent factor using R dplyr chain使用 R dplyr 链获取最频繁因子的值
【发布时间】:2017-03-28 22:01:24
【问题描述】:

我找到了一个简单的解决方案,可以使用

获取数据框中列的最频繁因子
names(which.max(table(df$column)))

但是如果我想在一个链中找到最常见的因子怎么办。是否有一个简单的代码可以为您提供因素的“模式”?

或者有没有一种方法可以将上述代码包含在一个链中?

我已经这样做了,这似乎是在浪费时间。

(df %>% group_by(column) %>% summarise(count=n()) %>% arrange(desc(count)))$count[1]

一个简单的代码将不胜感激,无需提供示例数据。谢谢!

【问题讨论】:

  • 为什么不能在第一个示例中将df 替换为.
  • 对不起,我不明白,我对 R 很陌生。我只想在链中执行此操作,因为我想首先过滤和变异 df,然后获得最多特定列的频繁因子。但是我不想在这个过程中创建一个新的df,然后做table方法。
  • df %>% top_n(1, column)
  • @Ricky 我的意思是,df %>% mutate(new_column = names(which.max(table(.$column))))
  • 另外,it's your responsibility to provide sample data 如果你想得到答案。

标签: r dplyr tidyr


【解决方案1】:

您可以使用来自magrittr%$% 中缀运算符:

df %$% column %>% table %>% which.max %>% names

或者你可以使用下面的语法,只使用管道:

df %>% {.$column} %>% table %>% which.max %>% names

甚至:

df %>% `$`("column") %>% table %>% which.max %>% names

【讨论】:

    猜你喜欢
    • 2018-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-22
    • 2017-01-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多