[R] function on columns of two arrays

arun smartpink111 at yahoo.com
Tue Aug 20 14:02:52 CEST 2013


Also, if you need ?mapply()
linRegFun<- function(x,y){
 res<- summary(lm(y~x))$coef}
 res1<-sapply(seq_len(ncol(a1)),function(i) summary(lm(b1[,i]~a1[,i]))$coef)
 res2<-mapply(linRegFun,a1,b1)
attr(res2,"dimnames")<-NULL
identical(res1,res2)
#[1] TRUE
A.K.




----- Original Message -----
From: arun <smartpink111 at yahoo.com>
To: "Folkes, Michael" <Michael.Folkes at dfo-mpo.gc.ca>
Cc: R help <r-help at r-project.org>
Sent: Tuesday, August 20, 2013 7:42 AM
Subject: Re: [R] function on columns of two arrays

Hi,
May be this helps.

  a1<- data.frame(a)
 b1<- data.frame(b)
 lapply(seq_len(ncol(a1)),function(i) lm(b1[,i]~a1[,i]))

 lapply(seq_len(ncol(a1)),function(i) summary(lm(b1[,i]~a1[,i]))$coef)

A.K.

----- Original Message -----
From: "Folkes, Michael" <Michael.Folkes at dfo-mpo.gc.ca>
To: r-help at r-project.org
Cc: 
Sent: Tuesday, August 20, 2013 3:34 AM
Subject: [R] function on columns of two arrays

I've spent a bit too long searching the help history and attempting to apply some logic to the following:
I have two 3D arrays each with same dim. I wish to run lm on the respective columns of each array, preferably without loops.
We often hear chatter that sometimes apply() won't be faster "just use a for loop" I'd like to test this one...
I just can't seem to wrap my brain around use of mapply on this task and am more surprised that I'm not finding a solution out there already.


a <- array(1:60,dim=5:3)
b <- a*3+10
lm(b[,1,1]~a[,1,1]) 
#and repeat for all rows and columns...

thanks in advance.
Michael

_______________________________________________________
Michael Folkes
Salmon Stock Assessment
Canadian Dept. of Fisheries & Oceans    
Pacific Biological Station

    [[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.




More information about the R-help mailing list