Use lapply for multiple regression with formula changing, not the dataset

前端 未结 4 1198
别那么骄傲
别那么骄傲 2020-12-18 09:35

I have seen an example of list apply (lapply) that works nicely to take a list of data objects, and return a list of regression output, which we can pass to Stargazer for n

相关标签:
4条回答
  • 2020-12-18 09:38

    Consider creating dynamic formulas from string:

    fit <- lapply(myvars, function(dvar)
        lm(as.formula(paste0(dvar, " ~ indus")),data=Boston))
    
    0 讨论(0)
  • 2020-12-18 09:38

    You can also use get():

    # make a list of independent variables
      list_x <- list("nox","crim")
    
    # create regression function
      my_reg <- function(x) { lm(indus ~ get(x), data = Boston) }
    
    # run regression
      results <- lapply(list_x, my_reg)
    
    0 讨论(0)
  • 2020-12-18 09:49

    This should work:

    fit <- lapply(myvars, function(dvar) lm(eval(paste0(dvar,' ~ wt')), data = Boston))
    
    0 讨论(0)
  • 2020-12-18 10:05

    You can also use a dplyr & purrr approach, keep everything in a tibble, pull out what you want, when you need it. No difference in functionality from the lapply methods.

    library(dplyr)
    library(purrr)
    library(MASS)
    library(stargazer)
    
    var_tibble <- tibble(vars = c("nox","crim"), data = list(Boston)) 
    
     analysis <- var_tibble %>% 
      mutate(models = map2(data, vars, ~lm(as.formula(paste0(.y, " ~ indus")), data = .x))) %>% 
      mutate(tables = map2(models, vars, ~stargazer(.x, type = "text", dep.var.labels.include = FALSE, column.labels = .y)))
    
    0 讨论(0)
提交回复
热议问题