Lapply in a nested list in R

641 Views Asked by At

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.

1

There are 1 best solutions below

2
On

The function cham_votes() expects the last two arguments to be integers. So, you have to convert them first as follows:

listafinal <- lapply(listafinal, function(x) c(x[1], lapply(x[2:3], as.integer)))

You need then to simply use lapply.

lapply(lista_final, funcao)

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 either NA or a tibble of classes tbl, tbl_df, and dataframe