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))) 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? Many thanks, Nerak -- View this message in context: http://r.789695.n4.nabble.com/apply-with-as-function-ifelse-with-2-logical-conditions-tp4403637p4403637.html Sent from the R help mailing list archive at Nabble.com.
Berend Hasselman
2012-Feb-20 11:41 UTC
[R] apply with as function ifelse with 2 logical conditions
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
Reasonably Related Threads
- function similar to ddply? + calculations based on previous row
- different way for a for loop for several columns?
- nls: how do you know if the model is significant?
- result numeric(0) when using variable1[which(variable2="max(variable2)"]
- Non-linear curve fitting (nls): starting point and quality of fit