Function in R is not taking the parameter correctly

Asked

Viewed 33 times

0

I am creating a function, but when calling the function, the parameter is not working when performing FILTER and SUM.

To select the column or to perform an n() type count, it works correctly.

Following example:

df <- data.frame(C1 = c(1,2,NA,3))

df_funcao = function(PERIODO){
  soma = df %>% 
  dplyr::select(PERIODO) %>%
  filter(PERIODO != 'NA') %>% 
  summarise(soma = sum(PERIODO))

return(soma)
  
}

df_2 <- df_funcao(C1)
df_2

Here gives a Character error, but is as numeric format.

Error: Problem with summarise() column soma. i soma = sum(PERIODO).
x invalid 'type' (Character) of argument
Run rlang::last_error() to see Where the error occurred.

1 answer

2


The current way evaluates the variable with {{.}}.

packageVersion("dplyr")
#[1] ‘1.0.7’

df_funcao = function(PERIODO){
  df %>% 
    dplyr::select({{PERIODO}}) %>%
    filter(!is.na({{PERIODO}})) %>% 
    summarise(soma = sum({{PERIODO}}))
}

df_2 <- df_funcao(C1)
df_2
#  soma
#1    6

The previous way (from dplyr version 0.6.0) was to transform the variable PERIODO in a quosure before assessing it.

df_funcao <- function(PERIODO){
  PERIODO <- enquo(PERIODO)
  df %>% 
    dplyr::select(!!PERIODO) %>%
    filter(!is.na(!!PERIODO)) %>% 
    summarise(soma = sum(!!PERIODO))
}

df_2 <- df_funcao(C1)
df_2
#  soma
#1    6

Editing

The function df_funcao above has only one argument and uses df who is in the .GlobalEnv because that’s how it’s in the question.

The best way is for functions to only use the arguments they are given. In tidyverse this means that in order to be used in a pipe, the first argument must be the data set, the data.frame.

The revised function is then as follows.

df_funcao2 <- function(x, PERIODO){
  x %>% 
    dplyr::select({{PERIODO}}) %>%
    filter(!is.na({{PERIODO}})) %>% 
    summarise(soma = sum({{PERIODO}}))
}

df_funcao2(df, C1)
df %>% df_funcao2(C1)
  • Worked out, hadn’t found anywhere else this way.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.