Skip to content
Prev 309013 / 398513 Next

ifelse reformulation

Hi,

Did you mean this?
group1<-c(40,50,"60",70)
#or
group2<-c(50,"var1","var2",60)

In either of the above cases, when you check
str(group1) # all are converted to character.
# chr [1:4] "40" "50" "60" "70"

?str(group2)
# chr [1:4] "50" "var1" "var2" "60"

Suppose, I am comparing the test1 dataset (x4: x6 columns) with group2
?apply(test1,1,function(x) ifelse(x[5:7]%in%group2,0,1)) # 2nd row is 50 for x4 column
?? #? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#[1,] 1 0 1 1 1 1 1 1 1? 1? 1? 1? 1? 1? 1
#[2,] 1 1 1 1 1 1 1 1 1? 1? 1? 1? 1? 1? 1
#[3,] 1 1 1 1 1 1 1 1 1? 1? 1? 1? 1? 1? 1

# final result
as.vector(apply(test1,1,function(x) ifelse(any(x[5:7]%in%group2),0,1)))
# [1] 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1

I guess it works.

BTW, in my previous reply, I made a mistake
as.vector(apply(test1,1,function(x) ifelse(any(x[4:6]%in%group),0,1)))? 
?????????????????????????????????????????????????????????????????????? ^^^^^^^ 
It should be 5:7.
group<-c(40,50,60,70)
as.vector(apply(test1,1,function(x) ifelse(any(x[5:7]%in%group),0,1)))
?#[1] 1 0 1 1 1 1 0 1 1 1 1 1 0 1 1

ifelse(test1$x4==40|test1$x4==50|test1$x4==60|test1$x4==70|test1$x5==40|test1$x5==50|test1$x5==60|test1$x5==70|test1$x6==40|test1$x6==50|test1$x6==60|test1$x7==70,0,1)
# [1] 1 0 1 1 1 1 0 1 1 1 1 1 0 1 1

?as.vector(apply(test1,1,function(x) ifelse(any(x[5:7]==40|x[5:7]==50|x[5:7]==60|x[5:7]==70),0,1)))
?#[1] 1 0 1 1 1 1 0 1 1 1 1 1 0 1 1


A.K.


















----- Original Message -----
From: brunosm <brunosm87 at gmail.com>
To: r-help at r-project.org
Cc: 
Sent: Thursday, October 25, 2012 12:55 PM
Subject: Re: [R] ifelse reformulation

Arun, thank you very much... but a new problem arose...

What if... in the variable group that i want to compare, there is numeric
and non numeric types?

Or, if you think its better, can i have two variables, one numeric and one
non numeric, and made the comparision?

Best regards,

Bruno

2012/10/12 arun kirshna [via R] <ml-node+s789695n4645988h70 at n4.nabble.com>
--
View this message in context: http://r.789695.n4.nabble.com/ifelse-reformulation-tp4645981p4647431.html
Sent from the R help mailing list archive at Nabble.com.
??? [[alternative HTML version deleted]]

______________________________________________
R-help at r-project.org mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.