Использование логического оператора "|" в R - PullRequest
0 голосов
/ 02 мая 2018

У меня есть код:

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] <- y и index <- 1*(w1|w2)? Предположим, что w1=0.2912 и w2=0.3732, что в результате x[i][w1|w2] <- y и index <- 1*(w1|w2) приведет к

Спасибо.

1 Ответ

0 голосов
/ 02 мая 2018

Давайте немного поэкспериментируем

Сначала несколько примеров значений

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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...