[R] simplifying the code

Spencer Graves spencer.graves at pdf.com
Mon Jun 27 23:25:14 CEST 2005


	  Have you considered a generalization of the following:

dat <- expand.grid(a=1:2, b=1001:1002); class(dat)
Xlate <- array(4:1, dim=c(2,2))
dat$c. <- Xlate[cbind(dat$a, dat$b-1000)]

	  spencer graves

Jim Brennan wrote:

> This gives the same answer for what you have supplied so far...
> 
>>dat$d<-ifelse((dat$b-dat$a)>=1000,dat$b-dat$a+1,0)
>>dat
> 
>    a    b    c    d
> 1  1 1001 1001 1001
> 2  2 1001    0    0
> 3  3 1001    0    0
> 4  4 1001    0    0
> 5  1 1002 1002 1002
> 6  2 1002 1001 1001
> 7  3 1002    0    0
> 8  4 1002    0    0
> 9  1 1003 1003 1003
> 10 2 1003 1002 1002
> 11 3 1003 1001 1001
> 12 4 1003    0    0
> 13 1 1004 1004 1004
> 14 2 1004 1003 1003
> 15 3 1004 1002 1002
> 16 4 1004 1001 1001
> 
> -----Original Message-----
> From: r-help-bounces at stat.math.ethz.ch
> [mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of alex diaz
> Sent: June 27, 2005 4:54 PM
> To: r-help at stat.math.ethz.ch
> Subject: [R] simplifying the code
> 
> dear list:
> 
> I made some corrections in the previous post that had 
> some mistakes.
> 
> I need help to achieve a simpler code to complete a 
> task I'm performing.
> here is an example:
> 
> dat<-expand.grid(a=seq(1,4),b=seq(1001,1004))
> 
> #I want to add a new column dat$c in that:
> 
> t1<-ifelse(dat$a==1&dat$b==1001,1001,0)
> t2<-ifelse(dat$a==2&dat$b==1002,1001,0)
> t3<-ifelse(dat$a==3&dat$b==1003,1001,0)
> t4<-ifelse(dat$a==4&dat$b==1004,1001,0)
> t5<-ifelse(dat$a==1&dat$b==1002,1002,0)
> t6<-ifelse(dat$a==2&dat$b==1003,1002,0)
> t7<-ifelse(dat$a==3&dat$b==1004,1002,0)
> t8<-ifelse(dat$a==1&dat$b==1003,1003,0)
> t9<-ifelse(dat$a==2&dat$b==1004,1003,0)
> t10<-ifelse(dat$a==1&dat$b==1004,1004,0)
> 
> dat$c<-t1+t2+t3+t4+t5+t6+t7+t8+t9+t10
> 
> My real data frame is much larger... I hope someone 
> can help me with this.
> 
> thanks for your help
> 
> a. diaz
> 
> 
> -------------------------------------------------
> Email Enviado utilizando o servigo MegaMail
> 
> ______________________________________________
> R-help at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide! http://www.R-project.org/posting-guide.html

-- 
Spencer Graves, PhD
Senior Development Engineer
PDF Solutions, Inc.
333 West San Carlos Street Suite 700
San Jose, CA 95110, USA

spencer.graves at pdf.com
www.pdf.com <http://www.pdf.com>
Tel:  408-938-4420
Fax: 408-280-7915




More information about the R-help mailing list