[R] apply with as function ifelse with 2 logical conditions
Berend Hasselman
bhh at xs4all.nl
Mon Feb 20 12:41:42 CET 2012
On 20-02-2012, at 10:40, Nerak wrote:
> Hi all,
> I have a question concerning using several conditions in an ifelse function
> used as the function in apply.
> I want to create a new value with the function ifelse ‘ object which can be
> coerced to logical mode “test[n,] >1 & test[n-1,]==0”
> With n I mean the row. I don’t know how I could do this without a loop. I
> want to avoid the usage of loops and was thinking about apply. This was what
> I was thinking about:
>
> test<-data.frame(C=c(0,0,0,0,5,2,0,0,0,15,12,10,6,0,0,0),B=c(0,0,0,0,9,6,2,0,0,24,20,16,2,0,0,0),F=c(0,0,0,0,6,5,1,0,0,18,16,12,10,5,1,0))
>
> test.b<-test[-(nrow(test)),]
> test.2b<-rbind(0,test.b)
> result<-as.data.frame(apply(test,M=2,function(x)ifelse((test>1&test.2b==0),1,0)))
>
You are not using the argument "x" in the ifelse.
For every column (you have 3) you are evaluating the ifelse condition.
> But I get 3 times the amount of rows than that I want…
> what I should achieve:
> test.result<-data.frame(C=c(0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0),B=c(0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0),F=c(0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0))
>
> Has someone a suggestions about what I’m doing wrong?
Simplify. You don't need apply. This'll do it
result <- ifelse((test>1) & (test.2b==0),1,0)
Berend
More information about the R-help
mailing list