繁体   English   中英

使用 tidyverse 在 r 中进行蒙特卡罗模拟

[英]Monte Carlo Simulation in r using tidyverse

这是我的数据:

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 使用蒙特卡罗模拟。

我已经完成了以下任务:

df2 <- df1 %>% sample_n(size = 1000, replace = TRUE)
 lm(y~x,data=df2)

我对么? 我们能做得更好吗? 我需要计算“a”和“b”然后模拟df1吗? 如果是的话,请你给我看看好吗?

这是另一个不太清楚的答案

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

一种很酷的方法是使用 infer 包

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM