Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在R中使用for循环在多个数据集上运行函数_R_Loops_Lm - Fatal编程技术网

在R中使用for循环在多个数据集上运行函数

在R中使用for循环在多个数据集上运行函数,r,loops,lm,R,Loops,Lm,假设我有几个数据集,d1,d2,d3,存储为列表: a<-1:10 d1<-data.frame(a) d2<-data.frame(a) d3<-data.frame(a) d1$b<-a*1 d2$b<-a*2 d3$b<-a*3 list<-c(d1,d2,d3) a我假设您希望函数如下所示: fxn<- function(param1, param2, dataset){ #run model according to par

假设我有几个数据集,
d1
d2
d3
,存储为列表:

a<-1:10
d1<-data.frame(a)
d2<-data.frame(a)
d3<-data.frame(a)
d1$b<-a*1
d2$b<-a*2
d3$b<-a*3

list<-c(d1,d2,d3)

a我假设您希望函数如下所示:

fxn<- function(param1, param2, dataset){
  #run model according to param1 and param2
  mod<-lm(dataset[,param1]~dataset[,param2])
  #calculate slope
  slope <- coef(mod)[2]
  #name it correctly
  names(slope) <- param2
  return(slope)
}
输出:

[[1]]
b 
1 

[[2]]
  b 
0.5 

[[3]]
        b 
0.3333333 
数据:


aTry,lappy(列表,fxn)。。。。不要使用列表作为列表的名称。它应该是这样的,这接近完美。是否有任何方法可以修改输出,使其打印一列数据集名称(d1、d2、d3),然后打印一列斜率(1、0.5、0.33333),而不是打印“输出”下列出的内容?
lapply(list, function(x) fxn('a','b',x))
[[1]]
b 
1 

[[2]]
  b 
0.5 

[[3]]
        b 
0.3333333 
a<-1:10
d1<-data.frame(a)
d2<-data.frame(a)
d3<-data.frame(a)
d1$b<-a*1
d2$b<-a*2
d3$b<-a*3

#made a small change
#stored the data.frames in a list 
#as I assume you probably wanted
list<-list(d1,d2,d3)
#first have the data.frames in a named list
list<-list(d1=d1,d2=d2,d3=d3)
temp <- data.frame(t(data.frame(lapply(list, function(x) fxn('a','b',x)))))
#and if you want rownames as a column
temp$dfs <- row.names(temp)

> temp
           b dfs
d1 1.0000000  d1
d2 0.5000000  d2
d3 0.3333333  d3