[R] Multiply each depth level of an array with another vector element

Greg Snow Greg.Snow at imail.org
Fri Aug 6 18:56:05 CEST 2010


?sweep

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Maurits Aben
> Sent: Thursday, August 05, 2010 2:00 PM
> To: r-help at r-project.org
> Subject: [R] Multiply each depth level of an array with another vector
> element
> 
> Suppose
> 
> x <- array(c(1,1,1,1,2,2,2,2), dim = c(2,2,2))
> 
> y <- c(5, 10)
> 
> 
> 
> Now I would like to multiply x[, , 1] with y[1] and x[, , 2] with y[2].
> 
> 
> 
> Possible solution is a for-loop:
> 
> for (i in 1:2) {
> 
> x[, , i] * y[i]
> 
> }
> 
> 
> 
> Another possible solution is this construction:
> 
> as.vector(t(replicate(nrow(x) * ncol(x), y))) * x
> 
> 
> 
> I find that these two solutions have a relatively large computation
> time (on
> larger arrays) and I suspect there should be solution with less
> computation
> time. Is there a faster method to perform this calculation (thus to
> multiply
> the depth of an array with respective vector elements)?
> 
> 
> 
> Best regards,
> 
> Maurits Aben
> 
> 	[[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