Maleeha Shahid
Maleeha Shahid

Reputation: 135

`select` in dplyr is not working inside the function

could you please tell me what's wrong with this function?

sum_it_up <- function(x){
    dplyr::select(x)|>
    dplyr::group_by(x)|>
    dplyr::summarize(
    count = sum(x)
)
}

-------------------------------------------------
So i used this function:

sum_it_all <- function(ds, x){ select(ds, x)|> dplyr::group_by( x ) |> dplyr::summarize( n = n() ) }


My variable is categorical:
`x = ("Yes, "No", "Not known", "Yes", "Yes", "No")`

I am getting the following error:

Error: Can't subset columns that don't exist. x Columns Yes, Yes, No, Yes, Yes, etc. don't exist. Run rlang::last_error() to see where the error occurred.


What you guys suggest @Ian Campbell @pax


Upvotes: 0

Views: 865

Answers (1)

QHarr
QHarr

Reputation: 84465

You have a missing ". Additionally, x should be passed in as a string, as per comments.

Count of entries within column x of dataframe ds:

library(dplyr)

sum_it_all <- function(ds, x) {
  select(ds, x) |>
    dplyr::group_by(x) |>
    dplyr::summarize(n = n())
}
x <- c("Yes", "No", "Not known", "Yes", "Yes", "No")
y <- runif(length(x))

sum_it_all(tibble(x, y), "x")

Upvotes: 1

Related Questions