[R] How to multiple the vector and variables from dataframe
arun
smartpink111 at yahoo.com
Mon Dec 31 04:20:17 CET 2012
HI Meng,
Just try:
rep(z,rach=nrow(dat))
#[1] 0.1 10.0 100.0
rep(z,chair=nrow(dat))
#[1] 0.1 10.0 100.0
rep(z,times=nrow(dat))
#[1] 0.1 10.0 100.0 0.1 10.0 100.0 0.1 10.0 100.0
rep(z,each=nrow(dat))
#[1] 0.1 0.1 0.1 10.0 10.0 10.0 100.0 100.0 100.0
rep(z,nrow(dat))
#[1] 0.1 10.0 100.0 0.1 10.0 100.0 0.1 10.0 100.0
#and
dat*rep(z,times=nrow(dat))
# x1 x2 x3
#1 0.1 0.4 0.7
#2 20.0 50.0 80.0
#3 300.0 600.0 900.0
dat*rep(z,nrow(dat))
# x1 x2 x3
#1 0.1 0.4 0.7
#2 20.0 50.0 80.0
#3 300.0 600.0 900.0
dat*rep(z,each=nrow(dat))
# x1 x2 x3
#1 0.1 40 700
#2 0.2 50 800
#3 0.3 60 900
A.K.
----- Original Message -----
From: meng <laomeng_3 at 163.com>
To: Andrius Druzinis <andrius.druzinis at gmail.com>
Cc: R help <r-help at r-project.org>
Sent: Sunday, December 30, 2012 9:24 PM
Subject: Re: [R] How to multiple the vector and variables from dataframe
Hi Andrius:
Thanks for your reply.
Your answer: dat*rep(z,each=nrow(dat)) works well.
But a strange thing happened:
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
I type:
dat*rep(z,rach=nrow(dat))
"rach" is "each" indeed,but I type "rach" mistakenly.
What's strange to me is :No error reply appears,but show me the result:
> dat*rep(z,rach=nrow(dat))
x1 x2 x3
1 0.1 0.4 0.7
2 20.0 50.0 80.0
3 300.0 600.0 900.0
Why does it happen,and what "rach" means?
Many thanks.
At 2012-12-31 00:08:26,"Andrius Druzinis" <andrius.druzinis at gmail.com> wrote:
Hi Meng,
A one-liner would be
dat*rep(z, each=nrow(dat))
Cheers,
Andrius
2012/12/30 meng <laomeng_3 at 163.com>
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.
[[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