1

I am trying to create an iterative function in R using a loop or array, which will create three variables and three data frames with the same 1-3 suffix. My current code is:

function1 <- function(b1,lvl1,lvl2,lvl3,b2,x) {

 lo1 <- exp(b1*lvl1 + b2*x)
 lo2 <- exp(b1*lvl2 + b2*x)
 lo3 <- exp(b1*lvl3 + b2*x)

 out1 <- t(c(lv1,lo1))
 out2 <- t(c(lvl2,lo2))
 out3 <- t(c(lvl3,lo3))

 out <- rbind(out1, out2, out3)
 colnames(out) <- c("level","risk")
 return(out)
}

function1(.18, 1, 2, 3, .007, 24)

However, I would like to iterate the same line of code three times to create lo1, lo2, lo3, and out1, out2 and out3. The syntax below is completely wrong because I don't know how to use two arguments in a for-loop, or nest a for loop within a function, but as a rough idea:

function1 <- function(b1,b2,x) {

for (i in 1:3) {

loi <- exp(b1*i + b2*x)
return(lo[i])

outi <- t(c(i, loi)
return(out[i])

}

out <- rbind(out1, out2, out3)
colnames(out) <- c("level","risk")
return(out)
}

function1(.18,.007,24)

The output should look like:

level  risk
1      1.42
2      1.70
3      2.03
llsabang
  • 143
  • 1
  • 10

1 Answers1

1

In R, the for loops are really inefficient. A good practice is to use all the functions from the apply family and try to use as much as possible vectorization. Here are some discussions about this.

For your work, you can simply do it with the dataframe structure. Here the example:

# The function
function1 <- function(b1,b2,level,x) {
  # Create the dataframe with the level column
  df = data.frame("level" = level)

  # Add the risk column
  df$risk = exp(b1*df$level + b2*x)

  return(df)
}

# Your variables
b1 = .18
b2 = .007
level = c(1,2,3)

# Your process
function1(b1, b2, level, 24)
#   level     risk
# 1     1 1.416232
# 2     2 1.695538
# 3     3 2.029927
Alexandre B.
  • 5,387
  • 2
  • 17
  • 40