[R] Creating a new var from conditional values in other vars

arun smartpink111 at yahoo.com
Thu Jun 13 01:04:30 CEST 2013


Hi `Bangali`,
You can type in the R Console ?with() 
?ifelse()
The details and some examples are there.


In addition to ?with(), you can use: ?within

dat1<-within(dat1,pattern<-ifelse(A>20 & B<=2.5 & C<=20,"Normal",ifelse(A <20 & B >2.5 & C >20,"Increased",ifelse(A >=20 & B >2.5 & C <=20,"Low","Other"))))

library(plyr)
?mutate()
dat1New<-mutate(dat1,pattern=ifelse(A>20 & B<=2.5 & C<=20,"Normal",ifelse(A <20 & B >2.5 & C >20,"Increased",ifelse(A >=20 & B >2.5 & C <=20,"Low","Other"))))
identical(dat1,dat1New)
#[1] TRUE
dat2<-transform(dat1,pattern=ifelse(A>20 & B<=2.5 & C<=20,"Normal",ifelse(A <20 & B >2.5 & C >20,"Increased",ifelse(A >=20 & B >2.5 & C <=20,"Low","Other")))) 
 identical(dat1,dat2)
#[1] TRUE
A.K.




Arun, 

Many thanks! The code works perfectly well. It seems that ifelse
 + with do the trick much better than if/else statement. Now  I need to 
understand the mechanichs of what you did. Can you provide a link on how
 to use with 
----- Original Message -----
From: arun <smartpink111 at yahoo.com>
To: R help <r-help at r-project.org>
Cc: 
Sent: Wednesday, June 12, 2013 4:03 PM
Subject: Re: Creating a new var from conditional values in other vars

Hi,
Try this:
set.seed(25)
dat1<- data.frame(A=sample(1:30,100,replace=TRUE),B=sample(1:35,100,replace=TRUE),C=sample(1:25,100,replace=TRUE))


dat1$pattern<-with(dat1,ifelse(A>20 & B<=2.5 & C<=20,"Normal",ifelse(A <20 & B >2.5 & C >20,"Increased",ifelse(A >=20 & B >2.5 & C <=20,"Low","Other"))))
head(dat1)
#   A  B  C pattern
#1 13 20  5   Other
#2 21 15  4     Low
#3  5 24  1   Other
#4 27 13  6     Low
#5  4  4 10   Other
#6 30 19 22   Other
A.K.




I am newbie to R coming from SAS (basic user). Quite a difficult move.... 
I have a dataframe named kappa exported from csv file 
kappa<-read.csv("kappacsv", header=TRUE, sep=";", dec=".") 
kappa contains 3 numeric vars (A,B and C) 
I want to create a new var called "pattern" depending on the values of the conditions in A, B and C 
I have tried many ways one has been this: 
kappa$pattern1<-99 # create a new numeric var in kappa dataframe 

if (A>=20 & B<=2.5 & C <=20){kappa$pattern<-"Normal"} 
else if (A <20 & B >2.5 & C >20){kappa$pattern<-"Increased"} 
else if (A >=20 & B >2.5 & C <=20){kappa$pattern<-"Low"} 
else {kappa$pattern<-“Other”} 
  
The code does not work and I get errors all the time. 
Any help will be greatly appreciated 
Thanks



More information about the R-help mailing list