Fitting a weighted linear regression model in R -coding "roadblock"

I am an inexperienced user of R and not a statistician, so apologies in advance if this query seems silly.

I have been asked to fit a weighted linear regression model in R.
The database has about 6400 cases. The dependent variable is continuous and there are 12 independent variables that I wish to include in the final model- of these 11 are continuous and 1 is a categorical variable with 8 different names, which I have converted into a factor variable. I have installed the lmtest package to my basic set.

I thought I would start gently with a simple multivariable linear model using just 1 numeric and the factor variable as predictors. Seemingly no problems, using the code:
model name <- lm(dependent variable ~ variable 1 + variable 2, data = my database) and the summary (model name) command produced an output.
Next I plotted fitted values versus residuals using the code:
plot(fitted(model name, resid(model name))
I also ran a studentized Breusch-Pagan test and it was highly significant.

My understanding is that, to fit a weighted linear regression model, one uses the same code as in unweighted model, but then add weights at the end (..., weights = name of weight object)

I have tried numerous ways to do this, such as
weights = 1/sd_variance
for which I got a message
Error in eval(extras, data, env) : object 'sd_variance' not found

or generating a weight object
<- 1 / lm(abs(model name$residuals) ~ model name$fitted.values)$fitted.values^2
for which I got a message
Error in model.frame.default(formula = dependent variable ~ variable 1 + variable 2 + :
variable lengths differ (found for '(weights)')

I have tried the process with just 2 of my numeric variables with no difference in outcome.

Is there some other intermediate step I must run before fitting the weighted model or there something different I should be doing or there a particular R package that I should be using?

Any advice gratefully received.

Best wishes,
Louis

You would need to create the variable sd_variance.

Thank you for this.

I will try to work out the code now. I also have some missing values in my database. Your advice shows me in what direction I need to go.

Best wishes,
Louis

This topic was automatically closed 42 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.