[R] if clause in data frame
arun
smartpink111 at yahoo.com
Sat Mar 30 05:35:19 CET 2013
HI,
I am not sure I understand it correctly.
Should this (m1*x1/m1) +n1*y1/n1) /(m1+n1) be (x1+y1)/(m1+n1)?
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))
}}}}
colnames(final)<- c("m1","n1","x1","y1")
final1<- within(final,{flag<- as.numeric((x1/m1)>(y1/n1));p11<-ifelse(flag==1, (x1+y1)/(m1+n1),x1/m1);p12<- ifelse(flag==1,(x1+y1)/(m1+n1),y1/n1)})
If you meant four new variables p11, p12, P11, P12,
then:
finalNew<-within(final,{flag<- as.numeric((x1/m1)>(y1/n1))})
lst1<-lapply(split(finalNew,finalNew$flag),function(x) {xNew<-x;if(all(xNew$flag==0)) within(xNew,{P11<-x1/m1;P12<- y1/n1}) else within(xNew,{p11<- (x1+y1)/(m1+n1); p12<- p11})})
library(plyr)
join_all(lst1,type="full")
head(join_all(lst1,type="full"))
# m1 n1 x1 y1 flag P12 P11 p12 p11
#1 4 4 0 0 0 0.00 0.00 NA NA
#2 4 4 0 1 0 0.25 0.00 NA NA
#3 4 4 0 2 0 0.50 0.00 NA NA
#4 4 4 0 3 0 0.75 0.00 NA NA
#5 4 4 0 4 0 1.00 0.00 NA NA
#6 4 4 1 1 0 0.25 0.25 NA NA
A.K.
________________________________
From: Joanna Zhang <zjoanna2013 at gmail.com>
To: arun <smartpink111 at yahoo.com>
Sent: Friday, March 29, 2013 2:58 PM
Subject: Re: if clause in data frame
thanks! What if I need to put more statement in if and else braces, like
if ((x1/m1) > (y1/n1)) {
p11<-(m1*x1/m1 + n1*y1/n1)/(m1+n1)
p12<-p11
}
else {
P11<- x1/m1
P12<- y1/n1
}
On Fri, Mar 29, 2013 at 12:47 PM, arun <smartpink111 at yahoo.com> 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)})
> 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
>
More information about the R-help
mailing list