Hi,
I am trying to create a function for value counts with groupby
method in R, i get an error if i call the function
This is the function:
valueCounts <- function (c) {
df |> select(c) |>
groupby(c) |> summarise(col_1 = n())
}
valueCounts('column1')
I get an error, what do I understand groupby function cannot take string key column. Please advise
A few observations:
First, the grouping function is group_by()
, not groupby()
Second, "embrace" the variable names in your function so R can find them.
Third, it is best practice to not use function names as variable names. Both c()
and df()
are functions in base R.
library(tidyverse)
valueCounts <- function (dframe, column) {
dframe |> select({{column}}) |>
group_by({{column}}) |> summarise(col_1 = n())
}
valueCounts(mtcars, cyl)
#> # A tibble: 3 × 2
#> cyl col_1
#> <dbl> <int>
#> 1 4 11
#> 2 6 7
#> 3 8 14
Created on 2023-04-21 with reprex v2.0.2
1 Like
Thank you, this is the one i was looking for {{parameter}},
How to call parameter in group_by()
system
Closed
June 3, 2023, 6:11am
4
This topic was automatically closed 42 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.