这是我的数据:
df1<-read.table(text=" x y
2 20
3 36
3 48
1 20
3 40
3 32
1 16
1 20
3 24
3 28
3 32
4 36
2 20
4 44
4 36
4 40
4 48
3 40
4 52
4 52
4 52
4 44
4 48
4 52
1 16
3 32
4 52
3 32
3 36
",header=TRUE)
我想通过df1使用Monte Carlo Simulation。
我已经完成以下任务:
df2 <- df1 %>% sample_n(size = 1000, replace = TRUE)
lm(y~x,data=df2)
我正确吗?我们可以做得更好吗?我需要计算“ a”和“ b”,然后模拟df1吗?如果可以,可以给我看看吗?
答案 0 :(得分:2)
这是另一个不太明确的答案
library(tidymodels)
set.seed(42)
bootstrap_data <- df1 %>%
rsample::bootstraps(100)
fit_lm_on_bootstrap <- function(split) {
lm(y ~ x,data= split)
}
boot_models <- bootstrap_data %>%
mutate(model = map(.x = splits,fit_lm_on_bootstrap),
tidy_results = map(model,tidy)) %>%
unnest(tidy_results)
boot_models %>%
filter(term == "(Intercept)") %>%
summarise_at(vars(estimate:p.value),mean)
# A tibble: 1 x 4
estimate std.error statistic p.value
<dbl> <dbl> <dbl> <dbl>
1 4.07 3.77 1.23 0.298
boot_models %>%
filter(term == "x") %>%
summarise_at(vars(estimate:p.value),mean)
# A tibble: 1 x 4
estimate std.error statistic p.value
<dbl> <dbl> <dbl> <dbl>
1 10.4 1.16 9.25 0.000000136
答案 1 :(得分:0)
一种很酷的方法是使用推断包
library(tidyverse)
library(infer)
df1 %>%
specify(y ~ x) %>%
generate(reps = 100, type = "bootstrap") %>%
calculate(stat = "correlation") %>%
summarise(odds = stat %>% mean(),sd = stat %>% sd)
df1 %>%
specify(y ~ x) %>%
generate(reps = 100, type = "bootstrap") %>%
calculate(stat = "slope") %>%
summarise(beta = stat %>% mean,sd = stat %>% sd)
答案 2 :(得分:-1)
您可以使用此代码。希望对您有所帮助。
test_hat_MLR_matrix <- matrix(NA,nrow = 1000, ncol = 9)
MLR_all_Models <- list()
for (i in 1:1000) {
id <- sample(seq_len(nrow(df1)),size = 20)
train <- df1[id,]
test <- df1[-id,]
MLR_Model <- lm(y~.,data =train)
test_hat_MLR <- predict(MLR_Model,test)
test_hat_MLR_matrix [i,] <- test_hat_MLR
MLR_all_Models [[i]] <- MLR_Model
}
第一个问题的答案是您的代码不正确,因为您需要为Monte Carlo进行引导并且尚未完成。而且我认为通过自举可以定义系数。