[R] apply regression to an array

David Winsemius dwinsemius at comcast.net
Tue Oct 6 23:39:18 CEST 2015


On Oct 6, 2015, at 10:42 AM, Adrienne Wootten wrote:

> R-Helpers,
> 
> I've seen some similar threads about this question online, but not quite
> what I'm looking for.  I apologize in advance if someone's already answered
> this and I just can't find it online.
> 
> Say that I have an array like test3 in the little example code I have below:
> 
> test1 = array(rep(1:10,each = 25),dim=c(5,5,10))
> test2 = array(rnorm(250,0,0.35),dim=c(5,5,10))
> test3 = test1+test2 # array with 5 rows, 5 columns, 10 slices
> 
> time=1:10
> 
> Where the dimensions are x, y, and time.  What I'd like to do is run a
> regression (for the sake of this example, say lm) on each x,y in time.  So
> for a single cell the formula might be test3[1,1,]~time, but I'd like to
> that for all cells.  The only way I can immediately think of is to use a
> loop, but I'm wondering if there's a way to do this without a loop.
> Perhaps with tapply?

 Would not be expecting a 5x5x10 results since you are using the last dimension to calculate a two parameters for each row and col. Why not use a loop? Doing it with an index is just a a disguised loop:

apply( test3, 1:2, function(x) coef(lm(x~time) ) ) # iterates over rows and cols.
# results is 5 x 5 x2

> 
> I'm actually doing a fourth order regression with a much larger array, but
> this simple example illustrates the question I have.
> 
> Many thanks for the help! Sorry if someone's already answered this and I
> can't find it.
> 
> Adrienne
> 
> -- 
> Adrienne Wootten
> Graduate Research Assistant
> State Climate Office of North Carolina
> Department of Marine, Earth and Atmospheric Sciences
> North Carolina State University
> 
> 	[[alternative HTML version deleted]]
> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list