[R] model.matrix and missing values

Martín Cañón martincmd at hotmail.com
Sun Nov 1 14:29:44 CET 2015


Hi to all.

I want to create a model matrix with variables that have missing values.

Recently I learned that na.pass/na.exclude and naresid are of great help in these type of cases (thanks, W. Dunlap).

Here's an example:

y <- c(1:5)
x1 <- c(1, 0, 1, 0, 1)
x2 <- c(1, NA, 1, NA, 1)
x3 <- c(NA, 0, 1, 0, NA)

mf <- model.frame(y ~ x1 + x2 + x3, na.action = "na.pass") 

mf

y x1 x2 x3
1 1  1  1 NA
2 2  0 NA  0
3 3  1  1  1
4 4  0 NA  0
5 5  1  1 NA

mm <- model.matrix(mf)

mm

 (Intercept) x1 x2 x3
3           1  1  1  1

attr(,"assign")
[1] 0 1 2 3

mm2 <- naresid(attr(mf, "na.action"), mm)

mm2

 (Intercept) x1 x2 x3
3           1  1  1  1

attr(,"assign")
[1] 0 1 2 3

As you can see, model.frame respects NA's. 

However, after model.matrix,  it doesn't work when I try to insert them in the right place with naresid.

Am I doing something wrong?

Thanks,


Martin

 		 	   		  
	[[alternative HTML version deleted]]



More information about the R-help mailing list