Home > database >  Defining a variable inside a loop inside a function
Defining a variable inside a loop inside a function

Time:04-11

So I have an assignment, where I have to show the convergence of regression coefficients to a certain value if the observed variable has a measurement error. The idea is to show the convergence depending on the number of observations as well as on the standard deviations of the variables.

I built the following function that should create a matrix with the regression coefficients depending on the number of observations. In a later step I would want to show this in a plot and then in a shiny webapp.

The function is:

Deviation <- function(N, sd_v = 1, sd_u = 1, sd_w = 1){
  b_1 <- 1
  b_2 <- 2
  for ( j in length(1:N)){
    v <- rnorm(j, mean = 0, sd_v)
    u <- rnorm(j, mean = 0, sd_u)
    w <- rnorm(j, mean = 0, sd_w)
    X <- u   w
    Y <- b_1   b_2 * X   v
    Reg <- lm(Y~X)
    if (j==1) {
      Coeffs <- matrix(Reg$coefficients)
    } else {
      Coeffs <- rbind(Coeffs, Reg$coefficients)  
    }
  }
  Coeffs <- as.data.frame(Coeffs)
  return(Coeffs)  
}
Deviation(100)

I always get the error that the variable Coeffs is not defined...

Thanks in advance!

CodePudding user response:

As pointed out in the discussion, one possible solution is to change the length(1:N), to simply 1:Nas written below. This works for me.

Deviation <- function(N, sd_v = 1, sd_u = 1, sd_w = 1){
  b_1 <- 1
  b_2 <- 2
  for ( j in 1:N){
    v <- rnorm(j, mean = 0, sd_v)
    u <- rnorm(j, mean = 0, sd_u)
    w <- rnorm(j, mean = 0, sd_w)
    X <- u   w
    Y <- b_1   b_2 * X   v
    Reg <- lm(Y~X)
    if (j==1) {
      Coeffs <- matrix(Reg$coefficients)
    } else {
      Coeffs <- rbind(Coeffs, Reg$coefficients)  
    }
  }
  Coeffs <- as.data.frame(Coeffs)
  return(Coeffs)  
}

followed by...

Deviation(100)
  • Related