Skip to content

if clause in data frame

5 messages · arun, David Winsemius

#
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)})
?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.
#
Forgot:

colnames(final)<- c("m1","n1","x1","y1")

before;
final1<-within(final,{flag<-ifelse(x1/m1>y1/n1, 1,0)})


----- Original Message -----
From: arun <smartpink111 at yahoo.com>
To: Joanna Zhang <zjoanna2013 at gmail.com>
Cc: R help <r-help at r-project.org>
Sent: Friday, March 29, 2013 1:47 PM
Subject: Re: if clause in data frame

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)})
?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.
#
On Mar 29, 2013, at 10:47 AM, arun wrote:

            
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) )
#
Yes, that is better.

I just copied the same function that the OP used.
A.K.
#
On Mar 29, 2013, at 1:48 PM, arun wrote:

            
This may be one of those instances where "=" is not an acceptable replacement for "<-". I get an error with that code whereas I get the desired result with:
David Winsemius
Alameda, CA, USA