# Load necessary libraries
library(plotly)
0.04/sqrt(0.025)
# Step 1: Simulate data
set.seed(42)
education_years <- runif(100, 5, 20)  # Random education years between 5 and 20
true_slope <- 2.5  # True slope for education effect on earnings
true_intercept <- 10  # True intercept
earnings <- true_intercept + true_slope * education_years + rnorm(100, 0, 5)  # Linear relationship with noise

# Step 2: Define SSR function
calculate_ssr <- function(intercept, slope, x, y) {
  predictions <- intercept + slope * x
  residuals <- y - predictions
  ssr <- sum(residuals ^ 2)
  return(ssr)
}


# Step 3: Generate a grid of intercept and slope values
intercepts <- seq(5, 15, length.out = 50)
slopes <- seq(1, 4, length.out = 50)
ssr_values <- outer(intercepts, slopes, Vectorize(function(i, s) calculate_ssr(i, s, education_years, earnings)))

# Step 4: Create a 3D surface plot
fig <- plot_ly(
  x = intercepts,
  y = slopes,
  z = ssr_values,
  type = "surface",
  colorscale = "Viridis",
  colorbar = list(title = "SSR")
)

# Customize plot layout
fig <- fig %>% layout(
  title = "3D Surface Plot of SSR for Education and Earnings",
  scene = list(
    xaxis = list(title = "Intercept"),
    yaxis = list(title = "Slope"),
    zaxis = list(title = "SSR")
  )
)

fig
















# To demonstrate confidence intervals using simulated data and multiple beta coefficients, we’ll go through the following steps in R:
#
#   1. **Simulate Data**: Create a dataset with a linear relationship between an independent variable \(X\) and a dependent variable \(Y\).
# 2. **Bootstrap to Generate Beta Coefficients**: Repeatedly sample from the data to estimate the slope (beta coefficient) for each sample.
# 3. **Calculate Confidence Interval**: Use the distribution of these beta estimates to calculate a confidence interval.
#

# Load necessary library
library(ggplot2)

# Step 1: Simulate data
set.seed(123)
n <- 100  # Sample size
x <- rnorm(n, mean = 10, sd = 2)  # Independent variable X
true_beta <- 2.5  # True slope
true_intercept <- 5  # True intercept
y <- true_intercept + true_beta * x + rnorm(n, mean = 0, sd = 2)  # Dependent variable Y with noise

# Step 2: Generate 100 beta coefficients using bootstrap sampling
n_boot <- 100  # Number of bootstrap samples
beta_estimates <- numeric(n_boot)

for (i in 1:n_boot) {
  sample_indices <- sample(1:n, replace = TRUE)  # Sample with replacement
  x_sample <- x[sample_indices]
  y_sample <- y[sample_indices]
  model <- lm(y_sample ~ x_sample)  # Fit linear model
  beta_estimates[i] <- coef(model)[2]  # Extract beta coefficient (slope)
}

# Step 3: Calculate confidence interval for the beta estimates
beta_mean <- mean(beta_estimates)
beta_sd <- sd(beta_estimates)
conf_int <- quantile(beta_estimates, probs = c(0.025, 0.975))  # 95% confidence interval

beat_mean

# Display confidence interval
cat("Mean Beta Estimate:", beta_mean, "\n")
cat("95% Confidence Interval for Beta:", conf_int, "\n")

# Step 4: Visualize beta estimates and confidence interval
beta_df <- data.frame(Beta_Estimates = beta_estimates)
ggplot(beta_df, aes(x = Beta_Estimates)) +
  geom_histogram(binwidth = 0.1, color = "black", fill = "skyblue") +
  geom_vline(xintercept = conf_int, color = "red", linetype = "dashed", size = 1) +
  geom_vline(xintercept = beta_mean, color = "blue", linetype = "solid", size = 1) +
  labs(
    title = "Bootstrap Distribution of Beta Estimates",
    x = "Beta Coefficient",
    y = "Frequency"
  ) +
  theme_minimal()


### Explanation of Each Step:
# - **Step 1**: Simulate data with a known linear relationship to establish ground truth.
# - **Step 2**: Bootstrap by repeatedly sampling with replacement to generate a distribution of beta coefficients.
# - **Step 3**: Calculate a 95% confidence interval from the bootstrap distribution.
# - **Step 4**: Visualize the distribution of beta estimates with the confidence interval marked in red and the mean estimate in blue.
#
# This will show the variability of beta estimates and the confidence interval around the estimated slope. Let me know if you’d like further customization on this demonstration!

# Load necessary library
library(ggplot2)

# Step 1: Simulate data
set.seed(123)
n <- 100  # Sample size
x <- rnorm(n, mean = 10, sd = 2)  # Independent variable X
true_beta <- 2.5  # True slope
true_intercept <- 5  # True intercept
y <- true_intercept + true_beta * x + rnorm(n, mean = 0, sd = 2)  # Dependent variable Y with noise

# Step 2: Generate 100 confidence intervals for beta coefficients using bootstrap
n_boot <- 100  # Number of bootstrap samples
conf_intervals <- data.frame(Lower = numeric(n_boot), Upper = numeric(n_boot))

for (i in 1:n_boot) {
  sample_indices <- sample(1:n, replace = TRUE)  # Sample with replacement
  x_sample <- x[sample_indices]
  y_sample <- y[sample_indices]
  model <- lm(y_sample ~ x_sample)  # Fit linear model
  beta_est <- coef(model)[2]  # Extract beta coefficient (slope)
  se_beta <- summary(model)$coefficients[2, 2]  # Standard error for beta

  # Calculate the 95% confidence interval for this beta estimate
  conf_intervals$Lower[i] <- beta_est - 1.96 * se_beta
  conf_intervals$Upper[i] <- beta_est + 1.96 * se_beta
}

# Step 3: Plot horizontal confidence intervals with true beta line
conf_intervals$Index <- 1:n_boot  # Index for plotting each interval

ggplot(conf_intervals, aes(y = Index)) +
  geom_errorbarh(aes(xmin = Lower, xmax = Upper), height = 0.3, color = "skyblue") +
  geom_vline(xintercept = true_beta, color = "red", linetype = "dashed", size = 1) +
  labs(
    title = "Confidence Intervals for Beta Estimates Across Bootstrap Samples",
    x = "Beta Coefficient",
    y = "Bootstrap Sample Index"
  ) +
  theme_minimal()
