Logical operators in if-else in R

霸气de小男生 提交于 2021-02-10 06:48:39

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/17085994/logical-operators-in-if-else-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!