'R - sapply does not seem to apply function to each element of a vector

I am trying to run a simulation to illustrate the unbiasedness of the OLS slope in simple linear regression when Y is affected by different levels of error variance. The following code seems to use only the first argument of sd <- c(1, 10). I guess something is wrong with how sd is used within the sapply() function but can't find the actual error.

set.seed(6578)
n <- 200 # sample size
n_samples <- 5000 # Number of samples drawn
sd <- c(1, 10) # Varying levels of error
x <- rnorm(n) # Covariate values

regressions <- function(x, sd) {
  z <- .4 * x + rnorm(n, 0, sd)
  fit_lm <- lm(z ~ x)
  slopes <- fit_lm$coefficients[2]
  return(slopes)
}

sample_slopes_varying_error <- sapply(sd, function(f) replicate(n_samples, regressions(x, sd)))

plot(density(sample_slopes_varying_error[, 1]), col = "red", main = "", xlab = "Slope estimates")
lines(density(sample_slopes_varying_error[, 2]), col = "blue")
abline(v = mean(sample_slopes_varying_error[, 1]), lty = "dashed", col = "red")
abline(v = mean(sample_slopes_varying_error[, 2]), lty = "dotted", col = "red")

apply(sample_slopes_varying_error, 2, sd) # Almost identical SDs. 
#> [1] 0.5282542 0.5353999


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source