Skip to content

data manipulation between vector and matrix

8 messages · C W, Sarah Goslee, arun

#
Hi,
On Wed, Dec 5, 2012 at 1:30 PM, C W <tmrsg11 at gmail.com> wrote:
Thanks for the actual reproducible example.
This will (note the modification to get x - mat):
[,1] [,2]
 [1,]    0  -19
 [2,]   -1  -20
 [3,]   -2  -21
 [4,]   -3  -22
 [5,]   -4  -23
etc.

--
Sarah Goslee
http://www.functionaldiversity.org
#
HI,
In addition to ?sweep(), you can use

apply(-mat,1,`+`,x) 

#or
library(plyr)
aaply(-mat,1,"+",x) 


A.K.






----- Original Message -----
From: C W <tmrsg11 at gmail.com>
To: Sarah Goslee <sarah.goslee at gmail.com>
Cc: r-help <r-help at r-project.org>
Sent: Wednesday, December 5, 2012 1:51 PM
Subject: Re: [R] data manipulation between vector and matrix

Thanks, Sarah.? First time heard about sweep(), it worked just the way I
wanted.
Mike
On Wed, Dec 5, 2012 at 1:42 PM, Sarah Goslee <sarah.goslee at gmail.com> wrote:

            
??? [[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.
#
Hi,

By comparing the different methods:
set.seed(5)
?mat1<-matrix(sample(1:1e6,1e6,replace=TRUE),ncol=10000)
?set.seed(25)
?x<-sample(1:1e6,10000,replace=TRUE)
?system.time(z1<-sweep(-mat1,2,x,"+"))
#?? user? system elapsed 
?# 0.076?? 0.000?? 0.069 
?system.time(z2<-apply(-mat1,1,`+`,x))
?#? user? system elapsed 
?# 0.036?? 0.000?? 0.031 
?system.time(z3<-aaply(-mat1,1,`+`,x))
#?? user? system elapsed 
#? 1.880?? 0.000?? 1.704 
?system.time(z4<- x-t(mat1))? #winner
#?? user? system elapsed 
?# 0.004?? 0.000?? 0.007 
?system.time(z5<- t(x-t(mat1)))
#?? user? system elapsed 
#? 0.008?? 0.000?? 0.009 


A.K.