I'm trying to apply a function to a nested list. I have the following lists:
lista_a <- list("PEC", "45", "1991")
lista_b <- list("PL", "4580", "1990")
lista_c <- list("PL", "200", "1980")
Which are nested in the following list:
lista_final <- list(lista_a, lista_b, lista_c)
I want to apply the following function (which uses the function cham_votes from congressbr package):
funcao <- function(x){ tryCatch(do.call(cham_votes, x), error=function(e){NA})}
To each element of lista_final. I am trying to use do.call because cham_votes has three inputs (type, number and year) and I want to use them all at the same time, therefore I needed a list.
Do you have any idea how can I apply this function to all elements of lista_final at once? The final result should be a list of dataframes.
Thanks for your help.
The function
cham_votes()expects the last two arguments to be integers. So, you have to convert them first as follows:You need then to simply use
lapply.This will return a list of elements each of which is of the same type as the return value of your function
funcao()which is eitherNAor a tibble of classestbl,tbl_df, anddataframe