编写一个带有if和else-if条件的R例程



support_cell<-function(I=2,J=2,zero,cell){
output<-c(0,0)
element<-c(zero[1], zero[2], cell[1], cell[2])
if (any(element<1) || any(element[c(1,3)]>I) || any(element[c(2,4)]>J)) stop("cell elements out of bound")


else if(cell[1]==zero[1] & cell[2]==zero[2]) {output}
else if(cell[1]==zero[1] & cell[2]!=zero[2]) {output[2]=1 }
else if(cell[1]!=zero[1] & cell[2]==zero[2]) {output[1]=1 }
else {output[c(1,2)]=1} 
return(output)
}

#example 1
zero<-c(1,2)
cell<-c(2,2)
support_cell(I,J,zero,cell)
[1] 1 0

我写这个函数是为了比较两个向量,输出是基于比较的另一个二进制向量。代码运行良好,但我知道应该有一种简单有效的方法来重写这些代码。我也想知道你的方法。

如果zero的值与cell的值匹配,我们可以使用!=进行匹配。我们为匹配返回0,为不匹配返回1。

support_cell<-function(I=2,J=2,zero,cell){
output <- as.integer(zero != cell)
return(output)
}
zero<-c(1,2)
cell<-c(2,2)
support_cell(I,J,zero,cell)
#[1] 1 0

您只是尝试按元素匹配这两个向量。R已经将该操作矢量化:

x <- c(1,2,6,3,8,0,4)
y <- c(1,7,6,2,8,0,3)
+(x == y)
# [1] 1 0 1 0 1 1 0

最新更新