简体   繁体   中英

How to pass weights in lm object as a variable from outside the function and refer the column name as weight in the model form?

I have a function to create lm object for multiple model iterations and the weights are an input to the function, which take different column values.

Here is the dummy:

x <-c(rnorm(10),NA)
df <- data.frame(y=1+2*x+rnorm(11)/2, x=x, wght1=1:11)

## Fancy weights as numeric vector

df$weight <- (df$wght1)^(3/4)
weight_var <- "weight"

model <-  lm(y~x,data=df,weights=df[, weight_var])

model$call[[4]]

See, the model$call[[4]] returns df[, weight_var] , I'd want it to return the column weight instead; which is the reference to that variable

Say I have columns a, b, c, d, e in the data, I want to run the model and check for weights possibility being d or e.

Thus, I define the if statement as this:

if (weight_var[[1]]=='') {
    model <- lm(formula = eqmodel, xdata)
  } else {
    model <- lm(formula = eqmodel, xdata, weights = xdata[,weight_var])
  }

where weight_var can be d or e . So that when we call:

model$call[[4]]

the output is either d or e .

However, when I see the model as:

Call:
lm(formula = eqmodel, data = xdata, weights = xdata[, weight_var])

I am okay with the eqmodel being equation of the model being specified from outside the function. However, I would like the weights to be d or e as it was passed. Is there a way to do it?

Updated

model$call[[i]] returns the values of lm() parameters letter by letter, so not only model$call[[4]] looks uninformative, but also model$call[[2]] returns the name of formula instead of the formula. Below a trick to improve it a little bit.

x <-c(rnorm(10),NA)
df <- data.frame(y=1+2*x+rnorm(11)/2, x=x, wght1=1:11)

## Fancy weights as numeric vector

df$weight <- (df$wght1)^(3/4)
weight_var <- "weight"
eqmodel <- as.formula("y~x")
xdata <- df

### unprocessed:
if (weight_var[[1]]=='') {
  model <- lm(formula = eqmodel, xdata)
} else {
  model <- lm(formula = eqmodel, xdata, weights = xdata[,weight_var])
}
summary(model)
#Call:
#lm(formula = eqmodel, data = xdata, weights = xdata[, weight_var])

### a little trick:
if (weight_var[[1]]=='') {
  model <- lm(formula = eqmodel, xdata)
} else {
  model <- lm(formula = eqmodel, xdata, weights = xdata[,weight_var])
  model$call[[4]] <- weight_var[[1]]
}
model$call[[2]] <- eqmodel
summary(model)

#Call:
#lm(formula = y ~ x, data = xdata, weights = "weight")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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