Errors caused by the inclusion of NA values in linear regression

Viewed 59

I want to do linear regression, but these are NA under one of the conditions. As you can see there are two conditions in my data, S: single and M: married. x2 and x3 are fixed effects and y are the dependent variables. x3 is not applicable for a single condition, so the data is all NA. I don't want to remove x3 as it is an important variable for the married condition. and i recieve this error:

Error in contrasts<-(*tmp*, value = contr.funs[1 + isOF[nn]]) :
contrasts can be applied only to factors with 2 or more levels.

I tried replacing NA with "0", but I'm not sure if that's the right way to do. Can anyone give me some suggestions? how should i write the lm code?

data <- data.frame(x1 = c("S", "S", "S", "M", "M", "M"), 
                   x2 = c(7, 7, 7, 1, 1, 2),
                   x3 = c(NA, NA, NA, 1, 1, 2),
                   y = c(4, 3, 2, 5, 5, 1))

lm(y~x1*x2*x3, data)

Can someone give me some help, please? (This is also the first time I post, I am not sure if I did it right.)

1 Answers

i tried to bring it to (technical) work, but it isn't so usefull as the others already said

data_df <- data.frame(x1 = c("S", "S", "S", "M", "M", "M"), 
                   x2 = c(7, 7, 7, 1, 1, 2),
                   x3 = c(NA, NA, NA, 1, 1, 2),
                   y = c(4, 3, 2, 5, 5, 1))

data_df$x1 <- as.integer(as.factor(data_df$x1))
data_df <- na.omit(data_df)

lm(y ~ x1*x2*x3, data_df)
Related