Write a loop in R that achieves the same result as combn (x,m,sum)

69 Views Asked by At

I have the function below:

Proposed <- function(N_b,Lanes,m,A,x.sqr,e_1,e_2,e_3,e_4,e_5) {
  e <- data.frame(e_1,e_2,e_3,e_4,e_5)
  CSi <- m * ((Lanes/N_b) + (max(A * combn(e,Lanes,sum)) / x.sqr))
  return(CSi)
}

I want to write a similar function but instead of using the function combn with the sum function, write a loop to go through as many columns of the e_1, e_2, e_3, e_4, e_5 variables as Lanes and select the max A * combn(...). This is because I later try to feed this through an nls and it does not like the way I define combn.

I need the function Proposed similar to the question Error when running nlsLM but works for nls.

A sample dataframe with the variables is given below.

> dput(DATA)
structure(list(Lanes = c(3, 3, 3, 3, 3, 3, 3), N_b = c(5, 5, 
5, 5, 5, 5, 5), A = c(-12, -12, -15, -9, -9, -15, -9), x.sqr = 
c(1440, 1440, 2250, 810, 810, 2250, 810), e_1 = c(21.8, 21.8, 
29, 14.6, 14.6, 29, 14.6), e_2 = c(9.8, 9.8, 17, 2.6, 2.6, 17, 
2.6), e_3 = c(-2.2, -2.2, 5, -9.4, -9.4, 5, -9.4), e_4 = 
c(-14.2, -14.2, -7, 0, 0, -7, 0), e_5 = c(0, 0, -19, 0, 0, -19, 0),  
m = c(0.85, 0.85, 0.85, 0.85, 0.85, 0.85, 0.85)), row.names = c(1L, 
7L, 20L, 25L, 26L, 53L, 89L), class = "data.frame")
1

There are 1 best solutions below

0
On

Although I am still looking for a loop, I was able to solve the issue by changing the way combn is defined in the function

Proposed2 <- function(N_b,Lanes,m,A,x.sqr,e_1,e_2,e_3,e_4,e_5,S,a,b) {
  e <- data.frame(e_1,e_2,e_3,e_4,e_5)
  CSi <- m * ((Lanes/N_b) + (max(A * combn(seq_along(e), 3, FUN = function(i) rowSums(e[i]))) / x.sqr) * (b*S^a))
  return(CSi)
}