本文介绍了R中if-else中的逻辑运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张称为mat的下表(5列3行):

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

正在执行的操作是 mat [1]/mat [1] + mat [2]

我正在测试以下内容:1)如果一行的两列均为零,则结果应为NA.2)如果一行中只有一列为零,另一列为非零,则继续进行计算.(即使分子为0,也可以)

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)

我当前在for循环中逐行使用此if-else结构:

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;}

我收到以下错误:

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

有没有更流畅的方法?

数字始终为整数,并且始终为0或更大.我想使用 apply ,但是如何直接将 apply 的结果分配到第三列?

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?

推荐答案

要获得结果,您不需要for循环,只需使用 ifelse().如果数据框 mat 中的列是数字而不是因素(如@Arun在评论中指出的那样),这将起作用.

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

这篇关于R中if-else中的逻辑运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-25 00:42