How to fit different nonlinear equations to different groups in R

Viewed 39

I have a dataset (dat) consisting of Site, Block, Variety, X, and Y. Such that Variety is within Block and Block within Site, i.e. Site/Block/Variety. See the link to a subset of the data: https://drive.google.com/file/d/1aXpu7ETbMHQXSNZRjUer37TlILe39bha/view?usp=sharing

I want to fit two nonlinear equations to the data (dat) by Site, Block and Variety. If Variety = 2, use the first equation, else, use the second equation. The goal is to have a data frame of this format: Site, Block, Variety, parm_a, param_b in different columns.

To do this, I used the nls_table function in forestmangr with the if statement. I used this code:

Re<-if(dat$Variety==2) {
  nls_table(dat, Y ~ (X / (param_a + param_b*X))^3, mod_start=c(param_a=1.5, param_b=0.7),   
            .groups = c("Site","Block","Variety"))
} else {
  (nls_table(dat, Y ~ param_a*X^param_b, mod_start=c(param_a=1.2, param_b=0.5),   
             .groups = c("Site","Block","Variety")))}

I got this Warning message: In if (dat$Variety == 2) { : the condition has length > 1 and only the first element will be used , which shows that only the first condition was used.

I would be grateful to get help from anyone.

Thank you.

1 Answers

1) dat$Variety is a vector but if can only compare scalars. Instead have separate runs for Variety 2 and the other varieties.

is.2 <- dat$Variety == 2
groups <- c("Site", "Block", "Variety")

out.2 <- nls_table(dat[is.2, ], Y ~ (X / (param_a + param_b * X))^3, 
  mod_start = c(param_a = 1.5, param_b = 0.7), .groups = groups)

out.not2 <- nls_table(dat[!is.2, ], Y ~ param_a * X ^ param_b, 
  mod_start = c(param_a = 1.2, param_b = 0.5), .groups = groups)

rbind(out.2, out.not2)

2) Another approach is to combine the two formulas.

fo <- Y ~ ifelse(is.2,  
            (X / (param_a + param_b * X))^3,
            param_a * X ^ param_b ) 
out <- nls_table(dat, fo, mod_start = c(param_a = 1.35, param_b = 0.6), 
  .groups = c("Site", "Block", "Variety"))
Related