How to do it through 1 step?
Hi,
How about this?
set.seed(5)
dat<-data.frame(x=sample(1:20,6,replace=TRUE),a=sample(20:40,6,replace=TRUE))
?dat1<-within(dat,{f=a/median(a);x_new=x*f})
?dat1
#?? x? a???? x_new???????? f
#1? 5 31? 5.081967 1.0163934
#2 14 36 16.524590 1.1803279
#3 19 40 24.918033 1.3114754
#4? 6 22? 4.327869 0.7213115
#5? 3 25? 2.459016 0.8196721
#6 15 30 14.754098 0.9836066
#or
?res<-do.call(data.frame,lapply(lapply(1,function(y) dat),function(y) {y$f<-y$a/median(y$a);y$x_new<-y$f*y$x;y}))
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: Monday, December 24, 2012 5:29 AM
Subject: Re:Re: [R] How to do it through 1 step?
To: arun <smartpink111 at yahoo.com>
Cc: R help <r-help at r-project.org>
Sent: Monday, December 24, 2012 5:29 AM
Subject: Re:Re: [R] How to do it through 1 step?
Yes,this is my final solution,but if I wanna add many new variables,and maybe the following "new variables" are computed based on the previous " new variables", this solution maybe difficult. At?2012-12-24?17:01:03,arun?<smartpink111 at yahoo.com>?wrote: >HI, > >Not?sure?if?this?works?for?you. >set.seed(5) >dat<-data.frame(x=sample(1:20,6,replace=TRUE),a=sample(20:40,6,replace=TRUE)) >?dat1<-transform(dat,f=a/median(a),x_new=x*(a/median(a))) >?head(dat1,2) >#???x??a????????f?????x_new >#1??5?31?1.016393??5.081967 >#2?14?36?1.180328?16.524590 >A.K. > > > > >-----?Original?Message?----- >From:?meng?<laomeng_3 at 163.com> >To:?r-help at r-project.org >Cc:? >Sent:?Monday,?December?24,?2012?12:55?AM >Subject:?[R]?How?to?do?it?through?1?step? > >A?data?set(dat),has?2?variables:?x?and?a,?and?100?rows. > >I?wanna?add?2?variables,and?call?the?new?data?set?dat1: >var1:f?=?a/median(a) >var2:x_new?=?x*f > >My?solution: >dat1<-transform(dat,f?=?a/median(a),x_new?=?x*f) >But?gets?error?reply?which?says?that?"f"?is?not?exits?since?dat?has?no?variables?called?"f". > >So?I?have?to?do?through?2?steps: >dat0<-transform(dat,f=a/median(a)) >dat1<-transform(dat0,x_new=x*f) > >How?to?do?it?through?1?step? > >Many?thanks! > > >????[[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. > ?