创建if +&声明

时间:2013-09-17 18:00:14

标签: r if-statement matrix

我正在使用R并且需要创建用于检查矩阵尺寸是否为3x3的代码。我使用if()检查nrowncol,但仍然使用正确的代码。任何帮助或建议都非常感谢。

localSmoother <- function(myMatrix = matrix(), 
  smoothingMatrix = matrix(1, nrow = 3, ncol = 3)) 
{ 
  if(class(smoothingMatrix) != "matrix") stop ("smoothingMatrix must be a matrix.")  
  if(ncol(smoothingMatrix) != "3" & if(nrow(smoothingMatrix) != "3") 
  stop ("smoothingMatrix must have dimensions of 3x3") 

  print(myMatrix) # see what myMatrix is.
  print(smoothingMatrix) # see what smoothingMatrix is.
  return(matrix(, nrow = 3, ncol = 3))
}

# # TEST the CODE:
localSmoother(myMatrix = diag(x = 2, nrow = 5, ncol = 5), smoothingMatrix = matrix(2, nrow = 5, ncol = 3))

# # Error in localSmoother(myMatrix = diag(x = 2, nrow = 5, ncol = 5), smoothingMatrix = matrix(2,  : 

# # smoothingMatrix must be 3x3

2 个答案:

答案 0 :(得分:2)

大多数情况下,您的条件中有两个if。你应该只有一个。

if(ncol(smoothingMatrix) != "3" & if(nrow(smoothingMatrix) != "3")
## should be
if(ncol(smoothingMatrix) != "3" & nrow(smoothingMatrix) != "3")

接下来,您的逻辑询问行数何时不是3 列数不是3.此条件按预期工作(返回TRUE并跟随{{中的stop语句1}}阻止)如果您的维度为if,但如果您的维度为c(5,4)则会失败。

c(5,3)

我会使用以下等效行之一:

x <- matrix(1:20,nrow=5)
dim(x)
# [1] 5 4
ncol(x) != "3" & nrow(x) != "3" 
# [1] TRUE

x <- matrix(1:12,nrow=3)
dim(x)
# [1] 3 4
ncol(x) != "3" & nrow(x) != "3" 
# [1] FALSE

注意两件事:

  1. 我正在使用逻辑运算符if(!(ncol(smoothingMatrix) == 3 && nrow(smoothingMatrix) == 3)) ## is the same as if(ncol(smoothingMatrix) != 3 || nrow(smoothingMatrix) != 3) &&而不是向量化运算符||&。试试|c(TRUE, FALSE) & TRUE
  2. 我使用的是数字形式c(TRUE, FALSE) && TRUE而不是字符3。 R会将这个数字强制转换为一个角色,所以相等测试在这里工作,但在其他情况下它可能会让你失望。
  3. 可能更容易比较矩阵的维度:

    "3"

    if(!isTRUE(all.equal(dim(smoothingMatrix),c(3L,3L)))) 是必需的,因为isTRUE会返回all.equal或描述差异的字符向量。请注意TRUE不会返回all.equal(1,0)而是返回FALSE描述差异的字符向量。if周围的任何all.equal语句如果相等不成立则会抛出错误。)

    all.equal(1,0)
    # [1] "Mean relative difference: 1"
    
    if(all.equal(1,0)) print(TRUE) 
    # Error in if (all.equal(1, 0)) print(TRUE) : 
    #   argument is not interpretable as logical
    

答案 1 :(得分:1)

@Blue Magister的回答非常好,解释很好,先去那里。

对于您的特定任务,您可能会发现stopifnot函数很有用。来自?stopifnot

  

stopifnot(...)如果...中的任何表达式都不是TRUE,则调用stop,产生一条错误消息,指出......的第一个元素不是真的。

您的代码可能是

stopifnot(is.matrix(smoothingMatrix),
          ncol(smoothingMatrix) == 3,
          nrow(smoothingMatrix) == 3)

缺点是错误消息的帮助有点小,好处是你不必自己编写它们,而且代码很好而且干净。

相关问题