[英]Lapply in a nested list in R
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): 我想应用以下函数(它使用来自
congressbr
包的cham_votes
函数):
funcao <- function(x){ tryCatch(do.call(cham_votes, x), error=function(e){NA})}
To each element of lista_final
. 到
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.call,因为
cham_votes
具有三个输入(类型,数字和年份),并且我想同时使用它们,因此我需要一个列表。
Do you have any idea how can I apply this function to all elements of lista_final
at once? 您是否知道如何将该函数一次
lista_final
所有元素? 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. 函数
cham_votes()
期望最后两个参数是整数。 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
。
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
这将返回元素的列表的每一个是相同的类型的函数的返回值的
funcao()
其是NA
或类一tibble tbl
, tbl_df
,和dataframe
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.