Your problem is related to non-standard evaluation
.
The smallest possible example of doing this is:
verificar_coluna <- function(data, coluna){
coluna_texto <- deparse(substitute(coluna))
coluna_texto %in% names(data)
}
> verificar_coluna(mtcars, mpg)
[1] TRUE
The function substitute
captures user-typed expression, and function deparse
turns it into a string.
The problem with that approach is if your function is called from within:
verificar_coluna2 <- function(data, coluna){
verificar_coluna(data, coluna)
}
> verificar_coluna2(mtcars, mpg)
[1] FALSE
So a safer approach is proposed by the package lazyeval
. To Vignette of it is very explanatory.
In practice, it is better to write a function:
verificar_coluna <- function(data, coluna){
coluna_texto <- lazyeval::expr_text(coluna)
coluna_texto %in% names(data)
}
Thus the two functions will function.
> verificar_coluna(mtcars, mpg)
[1] TRUE
> verificar_coluna2(mtcars, mpg)
[1] TRUE
I don’t understand. Your question is ambiguous to me. Do you need to check if there are any columns (either way) in the data frame or do you need to look for a specific column? If it’s a specific column, how do we identify it? What it has of special to differentiate it from the other columns that perhaps exist in this data frame?
– Marcus Nunes