model.matrix() with na.action=NULL?

前端 未结 4 1235
无人共我
无人共我 2020-12-13 13:08

I have a formula and a data frame, and I want to extract the model.matrix(). However, I need the resulting matrix to include the NAs that were found in the orig

4条回答
  •  暖寄归人
    2020-12-13 13:17

    Joris's suggestion works, but a quicker and cleaner way to do this is via the global na.action setting. The 'Pass' option achieves our goal of preserving NA's from the original dataset.

    Option 1: Pass

    Resulting matrix will contain NA's in rows corresponding to the original dataset.

    options(na.action='na.pass')
    model.matrix(ff, dat) 
    

    Option 2: Omit

    Resulting matrix will skip rows containing NA's.

    options(na.action='na.omit')
    model.matrix(ff, dat) 
    

    Option 3: Fail

    An error will occur if the original data contains NA's.

    options(na.action='na.fail')
    model.matrix(ff, dat) 
    

    Of course, always be careful when changing global options because they can alter behavior of other parts of your code. A cautious person might store the original setting with something like current.na.action <- options('na.action'), and then change it back after making the model.matrix.

提交回复
热议问题