Linear model when all occurrences of independent variables are NA

I am looking for suggestions on how to handle NA in linear regressions when all occurrences of the independent / explanatory variable are NA (i.e. x3below).

I know that the obvious solution is to exclude the independent / explanatory variable in question from the model, but I go through several areas and prefer not to have different functional forms for each region.

The following are some sample data:

set.seed(23409)
n <- 100

time <- seq(1,n, 1)
x1 <- cumsum(runif(n))           
y  <- .8*x1 + rnorm(n, mean=0, sd=2)
x2 <- seq(1,n, 1)       
x3 <- rep(NA, n)            
df <- data.frame(y=y, time=time, x1=x1, x2=x2, x3=x3)

# Quick plot of data
library(ggplot2)
library(reshape2)
df.melt <-melt(df, id=c("time"))

p <- ggplot(df.melt, aes(x=time, y=value)) + 
  geom_line() + facet_grid(variable ~ .)
p

I read the documentation for lmand made various settings na.actionwithout success:

lm(y~x1+x2+x3, data=df, singular.ok=TRUE)

lm(y~x1+x2+x3, data=df, na.action=na.omit)
lm(y~x1+x2+x3, data=df, na.action=na.exclude)

lm(y~x1+x2+x3, data=df, singular.ok=TRUE, na.exclude=na.omit)
lm(y~x1+x2+x3, data=df, singular.ok=TRUE, na.exclude=na.exclude)

lm , ( , NA) , ?

+5
2

:

set.seed(23409)
n <- 100

time <- seq(1,n, 1)
x1 <- cumsum(runif(n))           
y  <- .8*x1 + rnorm(n, mean=0, sd=2)
x2 <- seq(1,n, 1)       
x3 <- rep(NA, n)            
df <- data.frame(y=y, time=time, x1=x1, x2=x2, x3=x3)

replaceNA<-function(x){
  if(all(is.na(x))){
    rep(0,length(x)) 
  } else x

} 

lm(y~x1+x2+x3, data= data.frame(lapply(df,replaceNA)))
Call:
lm(formula = y ~ x1 + x2 + x3, data = data.frame(lapply(df, replaceNA)))

Coefficients:
(Intercept)           x1           x2           x3  
    0.05467      1.01133     -0.10613           NA  

lm(y~x1+x2, data=df)
Call:
lm(formula = y ~ x1 + x2, data = df)

Coefficients:
(Intercept)           x1           x2  
    0.05467      1.01133     -0.10613 

, , NA , 0. NA, ( qr-, , ). , summary(fit)$alias (. ?alias) .

, -, : lm [r]

+2

NA. model.matrix

 x1 <- 1:5
 x2 <- rep(NA,5)

 model.matrix(~x1+x2) 
     (Intercept) x1 x2TRUE
attr(,"assign")
[1] 0 1 2
attr(,"contrasts")
attr(,"contrasts")$x2
[1] "contr.treatment"

, .

- ...

make_formula <- function(variables, data, response = 'y'){
   if(missing(data)){stop('data not specified')}
   using <-  Filter(variables,f= function(i) !all(is.na(data[[i]])))

   deparse(reformulate(using, response))
 }

 variables <- c('x1','x2','x3')

make_formula(variables, data =df)

[1] "y ~ x1 + x2"

deparse , environment . lm , .

+3

All Articles