I found a code to loop over variables to estimate a series of OLS (linear models) from,
https://stats.idre.ucla.edu/r/codefragments/looping_strings/
The code is as follows:
varlist <- c("var1","var2","var3")
models <- lapply(varlist, function(x) {
lm(substitute(read ~ i, list(i = as.name(x))), data = hsb2)
})
lapply(models, summary)
When I want to replace the same syntax of linear models LM with robust linear models RLM, I receive an error.
varlist <- c("var1","var2","var3")
models <- lapply(varlist, function(x) {
rlm(substitute(read ~ i, list(i = as.name(x))), data = hsb2)
})
lapply(models, summary)
Any idea how I can achieve this?
DavoWW
August 26, 2021, 7:36am
2
Hi @sureshlp ,
Welcome to the RStudio Community Forum.
The MASS::rml()
function needs a formula as the first argument because it can accept either a formula or x=var1, y=var2
, whereas lm
only accepts a formula.
library(broom)
library(MASS)
data(mtcars)
varlist <- c("wt","disp")
models <- lapply(varlist, function(x) {
lm(substitute(mpg ~ i, list(i = as.name(x))), data = mtcars)
})
#lapply(models, summary)
lapply(models, glance)
#> [[1]]
#> # A tibble: 1 x 12
#> r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 0.753 0.745 3.05 91.4 1.29e-10 1 -80.0 166. 170.
#> # ... with 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>
#>
#> [[2]]
#> # A tibble: 1 x 12
#> r.squared adj.r.squared sigma statistic p.value df logLik AIC BIC
#> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
#> 1 0.718 0.709 3.25 76.5 9.38e-10 1 -82.1 170. 175.
#> # ... with 3 more variables: deviance <dbl>, df.residual <int>, nobs <int>
# Robust linear models RLM
models2 <- lapply(varlist, function(x) {
rlm(as.formula(substitute(mpg ~ i, list(i = as.name(x)))), data = mtcars)
})
#lapply(models2, summary)
lapply(models2, glance)
#> [[1]]
#> # A tibble: 1 x 7
#> sigma converged logLik AIC BIC deviance nobs
#> <dbl> <lgl> <logLik> <dbl> <dbl> <dbl> <int>
#> 1 3.06 TRUE -80.13923 166. 171. 280. 32
#>
#> [[2]]
#> # A tibble: 1 x 7
#> sigma converged logLik AIC BIC deviance nobs
#> <dbl> <lgl> <logLik> <dbl> <dbl> <dbl> <int>
#> 1 2.82 TRUE -82.40611 171. 175. 323. 32
Created on 2021-08-26 by the reprex package (v2.0.1)
worked like a charm. Thanks!
system
Closed
September 18, 2021, 5:00pm
4
This topic was automatically closed 21 days after the last reply. New replies are no longer allowed. If you have a query related to it or one of the replies, start a new topic and refer back with a link.