Hi Berend:
Thanks for your reply.

dat<-data.frame(x1=1:3,x2=4:6,x3=7:9)
z<-c(0.1,10,100)
#I wanna 0.1*x1,10*x2,100*x3

Option2 is similar as "dat*rep(z,each=length(z))",and the latter is simpler than Option2 in expression.










At 2012-12-31 00:31:42,"Berend Hasselman" <bhh@xs4all.nl> wrote:
>
>On 30-12-2012, at 11:26, meng <laomeng_3@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
>

	[[alternative HTML version deleted]]


