[R] Equivalent to matlab ".*" operator in R

peter dalgaard pdalgd at gmail.com
Thu Nov 20 18:16:07 CET 2014


Not sure you really want the overhead of sweep() for this, but logically, you want z as a vector or maybe 1d array since sweep() is designed as complimentary to apply(). I.e., you can sweep out marginal means using, say,

m <- matrix(c(5, 7, 9, 13), 2)
colmean <- apply(m, 2, mean)
sweep(m, 2, colmean, "-")

in which colmean is a vector. In general, apply() yields an array with fewer extents, and sweep expects one.

-pd

On 19 Nov 2014, at 16:00 , Dénes Tóth <toth.denes at ttk.mta.hu> wrote:

> Hi,
> 
> It is better to use sweep() for these kinds of problems, see ?sweep
> 
> y <- matrix(cbind(c(0, 0.5, 1),c(0, 0.5, 1)),ncol=2)
> z <- matrix(c(12, -6),ncol=2)
> sweep(y, 2, z, "*")
> 
> 
> Best,
>  Denes
> 
> 
> 
> On 11/19/2014 03:50 PM, Berend Hasselman wrote:
>> On 19-11-2014, at 15:22, Ruima E. <ruimaximo at gmail.com> wrote:
>> 
>>> Hi,
>>> 
>>> I have this:
>>> 
>>> y = matrix(cbind(c(0, 0.5, 1),c(0, 0.5, 1)),ncol=2)
>>> z = matrix(c(12, -6),ncol=2)
>>> 
>>> In matlab I would do this
>>> 
>>>> y .* x
>>> I would get this in matlab
>>> 
>>>> ans
>>> 0    -0
>>> 6    -3
>>> 12   -6
>>> 
>>> What is the equivalent in R?
>>> 
>> One way of doing this could be:
>> 
>> y * rep(z,1,each=nrow(y))
>> 
>> Berend
>> 
>>> Thanks
>>> 
>>> 	[[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.
>> ______________________________________________
>> 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.
> 
> ______________________________________________
> 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.

-- 
Peter Dalgaard, Professor,
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk  Priv: PDalgd at gmail.com



More information about the R-help mailing list