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

arun smartpink111 at yahoo.com
Mon Dec 31 03:51:35 CET 2012


HI Meng,

NO problem.
#In fact, 
sweep(dat,2,z,"*") #will be data.frame
 # x1  x2   x3
#1  2 120 2500
#2  5 200 5000
#3  8 300 6200
 str(sweep(dat,2,z,"*"))
#'data.frame':    3 obs. of  3 variables:
# $ x1: num  2 5 8
# $ x2: num  120 200 300
# $ x3: num  2500 5000 6200
A.K.






________________________________
From: meng <laomeng_3 at 163.com>
To: arun <smartpink111 at yahoo.com> 
Cc: R help <r-help at r-project.org> 
Sent: Sunday, December 30, 2012 9:40 PM
Subject: Re:Re: [R] How to multiple the vector and variables from dataframe


Hi,arun:
Yes,your answer is what I want.

A little different is :
data.frame(t(t(dat)*z))

Because I wanna get the "data frame"type, not matrix.

Thanks for your reply.







At 2012-12-31 00:59:43,arun <smartpink111 at yahoo.com> wrote:
>HI,
>Its not clear esp
>"
>I wanna do the following:
>10*x1,100*x2,1000*x3"
>
>Did you mean 10* dat[,1], 100*dat[,2], 1000*dat[,3]?
>dat<-read.table(text="
>x1    x2    x3
>0.2  1.2  2.5
>0.5  2      5
>0.8  3      6.2
>",sep="",header=TRUE)
>
>z<-c(10,100,1000) # 3rd element in your z is 100, which is confusing.
> t(t(dat)*z)
>#    x1  x2   x3
>#[1,]  2 120 2500
>#[2,]  5 200 5000
>#[3,]  8 300 6200
>
>A.K.
>
>
>
>
>
>
>
>----- Original Message -----
>From: meng <laomeng_3 at 163.com>
>To: R help <r-help at r-project.org>
>Cc: 
>Sent: Sunday, December 30, 2012 5:26 AM
>Subject: [R] How to multiple the vector and variables from dataframe
>
>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 .
>
>Any help?
>
>Many thanks!
>
>My best 
>
>
>
>    [[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.
>   




More information about the R-help mailing list