【发布时间】: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。