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

Asked

Viewed 1,756 times

3

I am writing a code in the R but it informs 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.

You can 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

1 answer

4

The if in R is not vectored, that is, it accepts only one value TRUE or FALSE. Turns out on your line:

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

What is inside the if: (BWGmax*(1-exp(-K*(MCisimulate-Xm)))) > WG returns a vector of TRUES and FALSES.

In this case you must use the function ifelse, testing 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:

  1. the condition to be tested on each vector element
  2. the value if true
  3. the value if false
  • Thank you Daniel solved my problem. Hugs!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.