Question

with a matrix like this

r<-20;
c<-6;
m1 <- round(matrix(runif(r*c), r, c)))

I would like to creat two new columns which are based on the last three using i.e. if/ifelse and boolean operators.

I tried the following but without success:

for (i in 1:dim(m1)[1]){
  if(sum(m1[i,4:6]==0)) {m1$Code1[i]<-0;m1$Code2[i]<-0}
  else if(sum(m1[i,4:6]==3)) {m1$Code1[i]<-5;m1$Code2[i]<-5}
  else if(m1[i,4]==0 && m1[,5]==1) {m1$Code1[i]<-3}
  else if(m1[i,4]==0 && m1[,6]==1) {m1$Code2[i]<-3}
  else if(m1[i,4]==1 && m1[,5]==0) {m1$Code1[i]<-2}
  else if(m1[i,4]==1 && m1[,6]==0) {m1$Code2[i]<-2} 
  else if(m1[i,4]==1 && m1[,5]==1) {m1$Code1[i]<-4}
  else if(m1[i,4]==1 && m1[,6]==1) {m1$Code2[i]<-4}  
}

My problem is if I can use the && in the if clause, but somehow this is not working. Can someone give me a hint why or come with a better option?

Thanks in advance, steph

Was it helpful?

Solution

I distill from your for loop that you want to perform the same action on the combination of line 4 and line 5 and on the combination of line 4 and 6. I think you then best can make a generic function and apply it on both combinations. I propose the following solution for your problem.

get.code <- function(x) {
 if(x[1] == 0 & x[2] == 0){0} else if (x[1] == 0 & x[2] == 1){3
 }else if(x[1] == 1 & x[2] == 1){4} else {2}
}

code1 <- apply(m1[,c(4,5)], 1, get.code)
code2 <- apply(m1[,c(4,6)], 1, get.code)
cbind(m1,code1, code2)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top