Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I have the following table (5 columns and 3 rows) called mat :

AC CA RES
1   0  
2   2 
1   3 
0   0 
0   1

The operation being performed is mat[1]/mat[1]+mat[2]

I am testing for the following : 1) If both columns of a row are zero, the result should be NA. 2) If only one column of a row is zero and the other has a non-zero number, proceed with calculation. (Even if the numerator is 0, that's okay)

I am currently using this if-else structure within a for-loop going row-wise:

if(mat[b,1]>=0|mat[b,2]>=0){mat[b,3]<-(mat[b,1]/(mat[b,1]+mat[b,2]));}
else{is.na(mat[b,3])=TRUE;}

I get the following error :

1: In Ops.factor(mat[b, 1], 0) : >= not meaningful for factors
2: In Ops.factor(mat[b, 2], 0) : >= not meaningful for factors

Is there a smoother way of doing this?

The numbers are always integer, and are always 0 or greater. I would like to use apply but how do I directly assign the results of apply into the 3rd column?

share|improve this question

1 Answer

To get result you don't need a for loop, just use ifelse(). This will work if columns in your data frame mat is numeric not the factors (as pointed out by @Arun in comment).

mat$RES<-ifelse(mat[,1]==0 & mat[,2]==0,NA,mat[,1]/(mat[,1]+mat[,2]))

 mat
  AC CA  RES
1  1  0 1.00
2  2  2 0.50
3  1  3 0.25
4  0  0   NA
5  0  1 0.00
share|improve this answer
1  
nice, but still that's not the error. you'll have to do: mat[] <- lapply(mat, function(x) as.numeric(as.character(x))) to convert the columns to numeric from factor. – Arun 24 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.