映射到两个列表 [英] mapply over two lists

查看:26
本文介绍了映射到两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近问了一个关于在两个列表上使用 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆