【问题标题】:R: using lapply with data frames and custom functionR:将 lapply 与数据框和自定义函数一起使用
【发布时间】:2015-08-12 17:09:03
【问题描述】:

我有一个关于将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 而是“逐个论证”,该函数会运行并给出预期结果。有人可以帮帮我吗?

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

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

prova
list()

很明显,我错过了什么!

【问题讨论】:

  • @nongkrong 谢谢。我想我在list 的数据帧上使用lapply,目的是将函数append 应用于每个dataframe 元素。事实上,append 将两个数据帧作为输入并给出一个数据帧作为输出。简而言之,我不确定我是否理解您的评论以及为什么它解释了我的 lapply 失败。能详细点吗?
  • 试试lapply(list1,function(x)apply(x[[1]],x[[2]]))
  • @MichaelChirico 谢谢,迈克尔。澄清一下:你的意思是lapply(list1, function(x) append(x[[1]], x[[2]]))?另外,x 是什么?你能解释一下吗?谢谢。
  • 您的 data1-data4 是矩阵而不是 data.frames,对吗?
  • 他们是data.frames

标签: r dataframe lapply


【解决方案1】:

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]])

这才是你想要的,对吧?

编辑:正如另一个答案所说,您也可以使用mapply,这有点整洁,但这是基于lapply 的解决方案。两种情况的结果都是一样的。

【讨论】:

  • 是的!这就是我想要的。我现在就试一试,然后报告!
【解决方案2】:

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

您可以改用Mapmapply。请注意,这里的参数顺序与lapply 相比是相反的:

result = Map(append, list1, list2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-11
    • 1970-01-01
    • 2019-11-21
    相关资源
    最近更新 更多