73427

Passing the weights argument to a regression function inside an R function

Question:

I am trying to write an R function to run a weighted (optional) regressions, and I am having difficulties getting the weight variable to work. Here is a simplified version of the function.

HC <- function(data, FUN, formula, tau = 0.5, weights = NULL){ if(is.null(weights)){ est <- FUN(data = data, formula = formula, tau = tau) intercept = est$coef[["(Intercept)"]] zeroWorker <- exp(intercept) } else { est <- FUN(data = data, formula = formula, tau = tau, weights = weights) intercept = est$coef[["(Intercept)"]] zeroWorker <- exp(intercept) } return(zeroWorker) }

The function works perfectly if I do not use the weights argument.

mod1 <- HC(data = mydata, formula = lin.model, tau = 0.2, FUN = rq)

But, throws an error message when I use the weights argument.

mod2 <- HC(data = mydata, formula = lin.model, tau = 0.2, FUN = rq, weights = weig)

I google the problem, and this post seems to be the closest to my problem, but I could still not get it to work. <a href="https://stackoverflow.com/questions/10858318/r-pass-argument-to-glm-inside-an-r-function" rel="nofollow">R : Pass argument to glm inside an R function</a>. Any help will be appreciated. My problem can be replicated with:

library("quantreg") data(engel) mydata <- engel mydata$weig <- with(mydata, log(sqrt(income))) # Create a fictive weigth variable lin.model <- foodexp~income mod1 <- HC(data = mydata, formula = lin.model, tau = 0.2, FUN = rq) # This works perfectly mod2 <- HC(data = mydata, formula = lin.model, tau = 0.2, FUN = rq, weights = weig) # throws an error.

Error in HC(data = mydata, formula = lin.model, tau = 0.2, FUN = rq, weights = weig) : object 'weig' not found

Answer1:

You have two problems. The error you're encountering is because you're trying to use the weigh variable without referencing it as coming from the mydata dataset. Try using mydata$weig. This will solve your first error, but you then get the actual one related to using the weights argument, which is:

Error in model.frame.default(formula = formula, data = data, weights = substitute(weights), : invalid type (symbol) for variable '(weights)'

The solution is to add the variable specified in HC's weights argument to the dataframe before passing it to FUN:

HC <- function(data, FUN, formula, tau = 0.5, weights = NULL){ data$.weights <- weights if(is.null(weights)){ est <- FUN(data = data, formula = formula, tau = tau) } else { est <- FUN(data = data, formula = formula, tau = tau, weights = .weights) } intercept = est$coef[["(Intercept)"]] zeroWorker <- exp(intercept) return(zeroWorker) }

Then everything works:

mod2 <- HC(data = mydata, formula = lin.model, tau = 0.2, FUN = rq, weights = mydata$weig) mod2 # [1] 4.697659e+47

Recommend

  • Why does `fastLm()` return results when I run a regression with one observation?
  • What is the Python (numpy or scipy or Pandas) equivalent for R's adjboxStats function?
  • rpy2 - 'R' object has no attribute 'nls'
  • catch NAs using linear model with dplyr
  • Invalid a session when user makes logout (Spring)
  • How to add multiple headers in Angular 5 HttpInterceptor
  • Forwarding All Traffic to http proxy (Tunneling)
  • IoC using autofac and WCF IParameterInspector
  • run Angular 4 + node API at a time
  • Perform specialised functionality on failure of a Scalatest
  • Google Street View container inside Shiny Application
  • Apply kurtosis to a distribution in python
  • How to avoid this Apple Siri https cracking scenario?
  • AndroidAnnotations Rest view response data
  • Why can't pass only 1 coulmn to glmnet when it is possible in glm function in R?
  • Verbose log abbriviations meaning in SVC, scikit-learn
  • CSS Border DIV as a Shape
  • double precision error when converting to scientific notation
  • Error: java.util.Arrays$ArrayList cannot be cast to java.util.ArrayList
  • PostgreSQL 9.1 timezones
  • Ransack search string arrays stored in db
  • How Can I Prevent Activation For Some ListView Items When The Selection Mode Is MultiChoiceModal?
  • Spring Security bcrypt encoding login is not working
  • Generic/Unknown HTTP Error with response code 0 using UnityWebRequest
  • How to programatically 'login' a user based on 'remember me' cookie when using j
  • Query to find the duplicates between the name and number in table
  • Eloquent update method change created_at timestamp
  • d3 v4 drag and drop with TypeScript
  • Why does access(2) check for real and not effective UID?
  • Illegal mix of collations for operation for date/time comparison
  • How to recover from a Spring Social ExpiredAuthorizationException
  • ILMerge & Keep Assembly Name
  • Arrow is showed instead of the material design version hamburger icon. Why doesn't syncState in
  • Large data - storage and query
  • WOWZA + RTMP + HTML5 Playback?
  • R: gsub and capture
  • Django query for large number of relationships
  • Why is Django giving me: 'first_name' is an invalid keyword argument for this function?
  • How can I use `wmic` in a Windows PE script?
  • How to push additional view controllers onto NavigationController but keep the TabBar?