Error: The condition has length 1 and only the first element will be used

3

I am writing a code in R but it reports the following error:

  

In if ((BWGmax * (1 - exp (-K * (MCisimulate - Xm))))> WG) {: the   condition has length > 1 and only the first element will be used.

Can you help me?

BWGmax <- 30
K <- 0.0118
Xm <- 21
SD <- 0.851636356306513
number <- 420
mean <- 28
MCic <- seq(from = 200, to = 270, by = 1.7)
MCisimulate <- rep(MCic, number)

WG <- c()

for(i in 1:number) { WG[i] <- ((sqrt(-2*log(runif(1, 0, 1)))*sin(2*pi*runif(1, 0, 1)))*SD)+(mean)} #mudar depois numeros por parametros
BW <- 0.0223*WG^0.8944
BWG <- if ((BWGmax*(1-exp(-K*(MCisimulate-Xm)))) > WG) { WG } else {  (BWGmax*(1-exp(-K*(MCisimulate-Xm)))) }
BWG
    
asked by anonymous 06.02.2016 / 14:45

1 answer

3

The if in R is not vectorized, that is, it only accepts a value TRUE or FALSE . It turns out that on your line:

BWG <- if ((BWGmax*(1-exp(-K*(MCisimulate-Xm)))) > WG) { WG } else {  (BWGmax*(1-exp(-K*(MCisimulate-Xm)))) }

What's inside if : (BWGmax*(1-exp(-K*(MCisimulate-Xm)))) > WG returns an array of TRUES and FALSES .

In this case you should use the ifelse function, which tests the specified condition, element by element of the vector. So you could rewrite this line as follows:

BWG <- ifelse((BWGmax*(1-exp(-K*(MCisimulate-Xm)))) > WG, 
              yes = WG, 
              no = (BWGmax*(1-exp(-K*(MCisimulate-Xm)))))

The function ifelse has three arguments:

  • the condition to be tested on each element of the vector
  • value if true
  • value if false
  • 06.02.2016 / 15:01