[R] How to multiple the vector and variables from dataframe

Neal H. Walfield neal at walfield.org
Sun Dec 30 17:40:24 CET 2012


At Sun, 30 Dec 2012 16:28:44 +0000,
Andrius Druzinis wrote:
> 
> Hi Neal,
> 
> Notice that c(2, 3) gets replicated into c(2, 3, 2, 3, 2, 3) and then
> multiplied by column. This is not the same as multiplying each column by
> the respective element in vector c(2, 3).

I think you mean multiplied by element.  

Here's a better solution using t to transpose the matrix:

dat=data.frame(x1=1:3, x2=11:13)
 as.matrix(dat)
     x1 x2
[1,]  1 11
[2,]  2 12
[3,]  3 13
t(as.matrix(dat)) * c(2, 3)
   [,1] [,2] [,3]
x1    2    4    6
x2   33   36   39

> 
> Andrius
> 
> 
> 2012/12/30 Neal H. Walfield <neal at walfield.org>
> 
> > At Sun, 30 Dec 2012 18:26:45 +0800 (CST),
> > meng wrote:
> > >
> > > hi all:
> > > Here's a dataframe(dat) and a vector(z):
> > >
> > > dat:
> > > x1     x2    x3
> > > 0.2   1.2   2.5
> > > 0.5   2      5
> > > 0.8   3      6.2
> > >
> > > > z
> > > [1]  10 100 100
> > >
> > > I wanna do the following:
> > > 10*x1,100*x2,1000*x3
> > >
> > > My solution is using the loop for z and dat(since the length of z is the
> > same as ncol  of dat),which is tedious.
> > > I wanna an efficient solution to do it .
> >
> > You could convert the data frame to a matrix:
> >
> > > dat=data.frame(x1=1:3, x2=11:13)
> > > dat
> >   x1 x2
> > 1  1 11
> > 2  2 12
> > 3  3 13
> > > as.matrix(dat) * c(3, 2)
> >      x1 x2
> > [1,]  3 22
> > [2,]  4 36
> > [3,]  9 26
> >
> > Neal
> >
> > ______________________________________________
> > 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