passing columnnames from functions

Hi everyone,

I have only just started using R and coming from programming in Python, I really like making functions. I want to apply the count method on a dataframe and assign the column name ('col_name') with the argument that is given to the function. My end goal is to loop through the column names (col_names <- colnames(df))) and apply the function to each column individually and to create a new dataframe based on these counts.

count_method  = function(col_name = "this_column"){
                   cur_counts <- df %>% count(col_name)

However, it always gives me an error that the column name is not found in the data frame ( Error: Must group by variables found in .data. Column col_name is not found*). I also tried to to apply rlang::sym to the argument and also tried it with the prefix !!. While this option at least didn't give me an error, it didn't select the column and returned a dataframe with the number of rows in the column col_name.

Does anyone know how to help?
I'd also appreciate any suggestions how to achieve my goal in a more efficient way.
Thanks and best,
Eva

Hello @evhuber ,

you started with (in my opinion) a tricky subject. But try this:

library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union

df = data.frame(
                f1 =  1:5,
                f2 = (1:5)^2)


sum_method <- function(df,col_name = "this_column"){
                   cur_counts <- df %>% summarize(x=sum({{col_name}}))
                   cur_counts$x
}

count_method <- function(df,col_name = "this_column"){
                   cur_counts <- df %>% count({{col_name}}) 
                   cur_counts 
}

sum_method(df,col_name=f1)
#> [1] 15
sum_method(df,col_name=f2)
#> [1] 55
count_method(df,col_name=f1)
#>   f1 n
#> 1  1 1
#> 2  2 1
#> 3  3 1
#> 4  4 1
#> 5  5 1
count_method(df,col_name=f2)
#>   f2 n
#> 1  1 1
#> 2  4 1
#> 3  9 1
#> 4 16 1
#> 5 25 1
Created on 2021-07-21 by the reprex package (v2.0.0)

Hi @HanOostdijk
Great, thanks a lot.
Actually the sum_method still gives me this error:
Error: Problem with summarise() column x.
:information_source: x = sum(pos_word_stem).
x invalid 'type' (character) of argument

But the count_method (which is what I need) works perfectly.

I understand: in my example I used numeric values.
For character values it will not work.

ah yes, that makes sense! Thanks again for your help :grinning: