使用逻辑运算符" |"在R

时间:2018-05-02 16:38:10

标签: r

我有一个代码:

generate.data <- function(nrep,K){
  if (K<=0){
      stop("K must be positive!\n")
  }
  x <- numeric(nrep) ; 
  for (i in 1:nrep){
    index<-0 ; 
    while (index<1){
      u1<-runif(1) ; 
      u2<-runif(1); 
      u3<-runif(1)
      tau <- 1+(1+4*K^2)^0.5 ; 
      rho <- (tau-(2*tau)^0.5)/(2*K)
      r <- (1+rho^2)/(2*rho) ; 
      z <- cos(pi*u1)
      f <- (1+r*z)/(r+z) ; 
      c <- K*(r-f)
      w1 <- (c*(2-c)-u2>0) ;
      w2 <- (log(c/u2)+1-c>=0)
      y <- sign(u3-0.5)*acos(f) ; 
      x[i][w1|w2] <- y
      index <- 1*(w1|w2)
    }
  }
  return( x )
}

我需要了解x[i][w1|w2] <- yindex <- 1*(w1|w2)的作用? 假设w1=0.2912w2=0.3732那么x[i][w1|w2] <- yindex <- 1*(w1|w2)会产生什么?

感谢。

1 个答案:

答案 0 :(得分:0)

让我们试一下

首先是几个示例值

x <- 9:2
i <- 3
y <- 100

w1 <- 0.2912
w2 <- 0.3732

然后

x
# 9 8 7 6 5 4 3 2

x[i]
# 7
# The ith value in the vector (in this case the 3rd)

w1|w2
# TRUE
# Are either w1 or w2 (or both) non-zero?    

w1 <- 0
w1|w2
# TRUE
# One of them are still non-zero

w2 <- 0
w1|w2
# FALSE
# Now neither are non-zero

w1 <- 0.2912
w2 <- 0.3732
# Re-asserting the values

x[i][w1|w2]
# 7
# Returns the 3rd value, as long as w1|w2 returns TRUE 
# (give the alternative a try)

x[i][w1|w2] <- y
# Replaces the value at position 3 with the value in y, 
# as long as w1|w2 returns TRUE

x[i]
# 100
# the new value at position 3

x
# 9   8 100   6   5   4   3   2
# The altered vector x, with the value of y (100) at position i (3)

index <- 1*(w1|w2)
index
# 1
# Multiplying TRUE or FALSE with 1 returns 1 or 0, respectively.
# Essentially shorthand for as.integer()