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

Berend Hasselman bhh at xs4all.nl
Sun Dec 30 17:31:42 CET 2012


On 30-12-2012, at 11:26, meng <laomeng_3 at 163.com> 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 .


Data:

xdat <- data.frame(x1=c(.2,.5,.8),x2=c(1.2,2,3),x3=c(2.5,5,6.2))
z <- c(10,100,1000)

Assuming you want  a dataframe as result you can do one of the following

Option 1:
------------
as.data.frame(sapply(1:length(z),function(k)xdat[k]*z[k]))

Option 2:
------------
as.data.frame(as.matrix(xdat)*rep(z,each=length(z)))

Option 3:
------------
as.data.frame(t(t(as.matrix(xdat))*z))

Option 4:
------------
as.data.frame(as.matrix(xdat)%*%diag(z))


The suggested solution

as.matrix(xdat)*z

results in

      x1   x2   x3
[1,]   2   12   25
[2,]  50  200  500
[3,] 800 3000 6200


and that doesn't seem to be what you want.

Berend




More information about the R-help mailing list