SAS_SQL_Spanman
SAS_SQL_Spanman

Reputation: 37

Unable to use "count" function in R

I am trying to use simply use count on 1 variable using the data frame and $ to call the variable. I am doing

count(customer_churn$Churn)

before installing dplyr I got following:

Error in count(customer_churn$Churn) : could not find function "count"

After installing dplyr and calling the library I get:

Error in UseMethod("summarise_") : no applicable method for 'summarise_' applied to an object of class "c('integer', 'numeric')"

I then tried using summarise instead and got the same error.

Upvotes: 1

Views: 19475

Answers (3)

nour
nour

Reputation: 9

You may use count function from plyr (not dplyr) which behaves a bit differently and works fine with vectors.

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

Upvotes: -2

Nareman Darwish
Nareman Darwish

Reputation: 1261

So generally I will assume that your data has IDs and flag whether customer is churned or not, you can count using the following methods.

Dplyr method

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 method

janitor::tabyl(customer_churn, Churn)

Base R method

table(customer_churn$Churn)

Upvotes: 0

akrun
akrun

Reputation: 887173

count expects a data.frame/tibble. According to ?dplyr::count.

x - a tbl() to tally/count.

Second issue is the error when we don't load the package after installing. It can be loaded by calling library(dplyr) or use explicitly dplyr::count

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

In base R, the table can be applied to the vector

table(customer_churn$Churn)

data

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

Upvotes: 6

Related Questions