On 30-12-2012, at 11:26, meng <laomen...@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

______________________________________________
R-help@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.

Reply via email to