R:将 lapply 与数据框和自定义函数一起使用

R: using lapply with data frames and custom function

我对使用 lapply 和数据帧列表有疑问。假设我有两个列表:

 list1<-list(data1,data2)
 list2<-list(data3,data4)

我想编写一个函数,将一个列和行从一个数据帧附加到另一个数据帧。这是我的功能:

append<-function(origin.data, destin.data){

vec.to.append<-origin.data[,1]

#add as the first column
destin.data<-cbind(vec.to.append, destin.data)

#add as first row
vec.to.append<-t(c(0, vec.to.append))
destin.data<-rbind(vec.to.append, destin.data)

return(destin.data)
}

如果我 运行

这很好用
append(list1[[1]], list2[[1]])

append(list1[[2]], list2[[2]])

但是当我尝试使用 lapply:

时出现错误
trial<-lapply(list1, append, destin.data=list2)

错误看起来很简单:

Error in rbind(vec.to.append, destin.data) : number of columns of matrices must match (see arg 2)

但是当我检查我的数据帧和向量的尺寸时,一切看起来都很好。另外,如果我不使用 lapply 而是使用 "argument by argument",函数 运行s 会给出预期的结果。有人可以帮我吗?

顺便说一下,我在这里看到了答案:Using lapply with changing arguments 但是在列表名称上应用我的函数会得到一个空结果:

prova<-lapply(names(list1), append, destin.data=list2)

prova
list()

很明显,我漏掉了什么!

lapply(list1, append, destin.data=list2) 等同于:

list(append(list1[[1]], list2),
     append(list1[[2]], list2)

这不是你想要的。如果你想按元素配对 list1 和 list2,你应该这样做:

lapply(seq_along(list1), function(i) append(list1[[i]], list2[[i]])

这相当于:

list(append(list1[[1]], list2[[1]]),
     append(list1[[2]], list2[[2]])

这是你想要的,对吧?

edit:正如其他答案所说,您也可以使用 mapply,它更简洁一些,但这是基于 lapply 的解决方案。两种情况下的结果都是一样的。

lapply 仅迭代 one 列表。您传递的最后一个参数按原样传递给函数(即函数 append 传递了所有 list2 而不是一个元素)。

您可以改用 Map or mapply。请注意,与 lapply:

相比,此处参数的顺序是相反的
result = Map(append, list1, list2)