[R] if clause in data frame

David Winsemius dwinsemius at comcast.net
Fri Mar 29 21:46:25 CET 2013


On Mar 29, 2013, at 10:47 AM, arun wrote:

> Hi,
> 
> 
> final<-data.frame()
>    for (m1 in 4:10) {
>        for (n1 in 4:10){  
>            for (x1 in 0: m1) {
>               for (y1 in 0: n1) {
> 
> final<- rbind(final,c(m1,n1,x1,y1))
> res}}}}
>  final1<-within(final,{flag<-ifelse(x1/m1>y1/n1, 1,0)})

That looks likely to be extremely slow. 'rbind.data.frame' is notoriously slow when applied iteratively in loops.

Couldn't this just be:

dat <- expand.grid(m1 = 4:10, n1 = 4:10, x1 = 0: m1, y1 = 0: n1) 
final= within(dat, flag=as.numeric( x1/m1>y1/n1) )

-- 
David.

>  head(final1)
> #  m1 n1 x1 y1 flag
> #1  4  4  0  0    0
> #2  4  4  0  1    0
> #3  4  4  0  2    0
> #4  4  4  0  3    0
> #5  4  4  0  4    0
> #6  4  4  1  0    1
> 
> 
> Also, just by looking at your code, you have "flag" and "flap".
> 
> A.K.
> 
> 
> 
> ________________________________
> From: Joanna Zhang <zjoanna2013 at gmail.com>
> To: arun <smartpink111 at yahoo.com> 
> Sent: Friday, March 29, 2013 10:56 AM
> Subject: if clause in data frame
> 
> 
> Why the if clause code not working here?
> 
> final<-data.frame()
>    for (m1 in 4:10) {
>        for (n1 in 4:10){  
>            for (x1 in 0: m1) {
>               for (y1 in 0: n1) {
> 
> if (x1/m1>y1/n1)  { flag<-1}
> else {flap<-0}
> 
> final<-rbind(final, c(m1,n1,flag, x1,y1))
> }}
> }}
> colnames(final)<-c("m1","n1","flag","x1","y1") 
> final
> 


David Winsemius
Alameda, CA, USA



More information about the R-help mailing list