映射两个列表 [英] mapply over two lists
问题描述
我最近问了一个关于在两个列表上使用apply
函数的问题.每个列表都是通过拆分大数据帧而创建的数据帧的列表.对于函数每次运行,我都希望从mylist1
中的第一个元素(一个数据帧)获取矢量,并从mylist2
中的第一个元素(一个数据帧)获取一些矢量,并使它们彼此回归.然后移至下一个mylist1
元素和mylist2
元素.有效地,该函数获取两个具有相同元素数量的列表,并获取一对(每个列表中的一个)并进行处理.
I recentely asked a question about using an apply
function over two lists. Each list is a list of data frames created by splitting a large dataframe. For each time the function runs I want to take vectors from the first element (a dataframe) in mylist1
and some vectors from the first element (a dataframe) in mylist2
and regress them against each other. Then move onto the next mylist1
element and mylist2
element. Effectively the function takes two lists with the same number of elements and takes a pair (one from each list) and plays about with them.
我尝试了以下操作,但是得到的结果不是我想要的:
I tried the following, but the results I get are not what I want:
a1<-c(1:5,rep(0,5))
a2<-c(1:5,10:6)
b2<-c(rep(100,5),rep(50,5))
z<-c(rep("part1",5),rep("part2",5))
df1<-data.frame(a1,z)
df2<-data.frame(a2,b2,z)
mylist1<-split(df1,z)
mylist2<-split(df2,z)
myfunction<-function(x,y)
{
meana <- mean(x$a)
meanb <- mean(y$b)
model<-lm((x$a)~(y$a))
return(c(model$coefficients[2],meana=meana,meanb=meanb))
}
result <- mapply(myfunction,x=mylist,y=mylist2)
#result
# x y
#y$a 1 -1
#meana 3 8
#meanb 100 50
我想要的是:
#y$a 1 0
#meana 3 0
#meanb 100 50
#e.g. the results in the first row are from lm((mylist1[[1]][,1])~(mylist2[[1]][,1])) and lm((mylist1[[2]][,1])~(mylist2[[2]][,1]))
推荐答案
我运行了您的代码并得到
I ran your code and got
> result <- mapply(myfunction,x=mylist1,y=mylist2)
> result
part1 part2
y$a 1 0
meana 3 0
meanb 100 50
您有错字
result <- mapply(myfunction,x=mylist,y=mylist2)
我改为
result <- mapply(myfunction,x=mylist1,y=mylist2)
也许这就是问题
这篇关于映射两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!