【问题标题】:Unable to use "count" function in R无法在 R 中使用“计数”功能
【发布时间】:2020-01-02 16:57:56
【问题描述】:

我正在尝试简单地使用 count 使用数据框和 $ 来调用变量的 1 个变量。我在做

count(customer_churn$Churn)

在安装 dplyr 之前,我得到了以下信息:

计数错误(customer_churn$Churn):找不到函数“count”

安装dplyr 并调用我得到的库后:

UseMethod("summarise_") 中的错误: 没有适用于“summarise_”的方法应用于“c('integer', 'numeric')”类的对象

然后我尝试改用summarise 并得到同样的错误。

【问题讨论】:

  • 您能提供一些数据吗?
  • 关于第一个错误,你必须先安装包才能使用它的功能。第二个,read the docs 了解如何调用count 以及调用什么(数据框,而不是向量)

标签: r


【解决方案1】:

count 需要一个 data.frame/tibble。根据?dplyr::count

x - 一个 tbl() 来计数/计数。

第二个问题是安装后没有加载包的错误。可以通过调用library(dplyr)或者显式使用dplyr::count来加载

library(dplyr)
customer_churn %>%
      count(Churn)

base R 中,table 可以应用于vector

table(customer_churn$Churn)

数据

set.seed(240)
customer_churn <- data.frame(Churn = sample(1:5, 50, replace =TRUE))

【讨论】:

    【解决方案2】:

    所以一般我会假设你的数据有 ID 并标记客户是否流失,你可以使用以下方法进行计数。

    Dplyr 方法

    library(dplyr)
    
    customer_churn <-
      data.frame(
        id = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10),
        Churn = c(0, 0, 0, 0, 0, 1, 0, 1, 0, 1)
      )
    
    customer_churn %>%
      count(Churn)
    
    # A tibble: 2 x 2
    # Groups:   Churn [2]
    # Churn     n
    # <dbl> <int>
    #  0     7
    #  1     3
    

    看门人方法

    janitor::tabyl(customer_churn, Churn)
    

    基础 R 方法

    table(customer_churn$Churn)
    

    【讨论】:

      【解决方案3】:

      您可以使用plyr(不是dplyr)中的count 函数,它的行为有点不同,并且适用于向量。

      plyr::count(iris$Species)
      #>            x freq
      #> 1     setosa   50
      #> 2 versicolor   50
      #> 3  virginica   50
      

      【讨论】:

      • 为什么?他们询问了 dplyr 中的一个函数,而不是 plyr,无论如何它大部分都已退休
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-08
      • 2017-02-07
      • 2017-09-18
      • 2021-03-05
      • 2016-11-10
      相关资源
      最近更新 更多