首页 > 解决方案 > 使用 lapply 在嵌套的多变量列表上应用函数

问题描述

我的功能采用以下形式

myfun<-function(Year, ID, Species, Abundance, resamps) {do something}

"resamps" 表示重新采样,它需要一个数字(例如 20)

我在数据帧上应用该函数没有问题,因为它接受以下形式的数据:

<-myfun(mydata$Year, mydata$Bay, mydata$Species, mydata$Abundance, 20)

我需要将此功能应用于具有以下结构的列表

 $ TX_ARAB:Classes ‘tbl_df’, ‘tbl’ and 'data.frame':    308670 obs. of  4 variables:
  ..$ Year     : chr [1:308670] "1982" "1982" "1982" "1982" ...
  ..$ Bay      : chr [1:308670] "TX_ARAB" "TX_ARAB" "TX_ARAB" "TX_ARAB" ...
  ..$ Species  : chr [1:308670] "Anchoa mitchilli" "Brevoortia patronus" "Dorosoma cepedianum" "Leiostomus xanthurus" ...
  ..$ Abundance: num [1:308670] 1 243 1 24 3 6 26 6 1 1 ...
 $ TX_COCB:Classes ‘tbl_df’, ‘tbl’ and 'data.frame':    344467 obs. of  4 variables:
  ..$ Year     : chr [1:344467] "1982" "1982" "1982" "1982" ...
  ..$ Bay      : chr [1:344467] "TX_COCB" "TX_COCB" "TX_COCB" "TX_COCB" ...
  ..$ Species  : chr [1:344467] "Anchoa mitchilli" "Micropogonias undulatus" "Ariopsis felis" "Archosargus probatocephalus" ...
  ..$ Abundance: num [1:344467] 6 17 10 1 16 3 2 42 1 11 ...

当我这样做时它不起作用并不奇怪

d = lapply(mylist, myfun, resamps = 20)

我不知道如何让函数相应地使用列表中的相关对象,因为当它应用于数据帧时,我必须将数据名称与对象一起传递。

标签: rlistfunction

解决方案


推荐阅读