I want to make a simple function in R that works with data.frames/tibbles or with a data.table. So I created a new method:
pesquisarComposicao <- function(BASE, ...) {
UseMethod("pesquisarComposicao")
}
Then I created the method for data.frames, which shows is a very simple searching function. This works very well.
pesquisarComposicao.data.frame <- function(BASE, TERMO, CAMPO = DESCRICAO) {`
BASE |>
filter(grepl(pattern = {{TERMO}}, x = {{CAMPO}}))
}
But the data.table method below is not working (I was following the instructions here):
pesquisarComposicao.data.table <- function(BASE, TERMO,
CAMPO = "DESCRICAO DA COMPOSICAO") {
# filter_col <- NULL
# filter_val <- NULL
BASE[filter_col %like% filter_val,
env = list(
filter_col = CAMPO,
filter_val = I(TERMO)
), verbose = FALSE]
}
I have tried to insert filter_col = NULL and filter_val = NULL in order to avoid the following error:
Error in pesquisarComposicao.data.table(BASE = sinteticoSINAPI, TERMO = "PEITORIL") : object 'filter_col' not found
But then I obtained another error:
Error in grepl(pattern, vector, ignore.case = ignore.case, fixed = fixed, : invalid 'pattern' argument
I think it's weird, because when I was not yet using methods, but coded a function that should work for data.tables and simple data.frames (verified internally if the object was one of type or another), this piece of code above was working fine (and I didn't need the filter_col = NULL and filter_val = NULL). Why did it worked for a single function but it did not work as a method?
dplyranddata.tableare quite different. What is TERMO, what is COMPO? It might be easier to convert from tibble or data.table to data.frame, do the operation, and coerce back. Of course, this comes with the cost of coercion, but there are tricks likequick_dflibrary(data.table); BASE[grepl(pattern=TERMO, x=get(CAMPO))]?data.frametodata.tableinside the function, but I found out that the searching withdata.tablebecame slower than with the original one, withdplyr. I think that was because of the conversion, then I decided to create methods.data.tablebecause I have addeddata.tableas a dependency of the package, so I don't have to load it inside the function.