[R] na.action in xtabs - how to include NAs?
David L Carlson
dcarlson at tamu.edu
Wed Sep 30 18:08:31 CEST 2015
If you are going to do this routinely or with many factors, you can build NA into each of the factors, but that will affect other operations:
> xNA <- lapply(x, factor, exclude=NULL)
> xtabs(~a+b, xNA)
a 2 3 4 <NA>
1 0 0 0 1
2 1 0 0 0
3 0 1 0 0
<NA> 0 0 1 0
David L Carlson
Department of Anthropology
Texas A&M University
College Station, TX 77840-4352
From: R-help [mailto:r-help-bounces at r-project.org] On Behalf Of Dimitri Liakhovitski
Sent: Wednesday, September 30, 2015 10:22 AM
To: William Dunlap
Subject: Re: [R] na.action in xtabs - how to include NAs?
Thank you very much, Bill - it worked.
Wow, that's very wordy!
On Wed, Sep 30, 2015 at 11:09 AM, William Dunlap <wdunlap at tibco.com> wrote:
> Try both na.action=na.pass and exclude=NULL, the first is for
> xtabs' call to model.frame and the second for when it prepares
> the data from model.frame's output for a call to table.
> xtabs(formula = ~a + b, data = x, na.action = na.pass, exclude = NULL)
> Bill Dunlap
> TIBCO Software
> wdunlap tibco.com
> On Wed, Sep 30, 2015 at 7:56 AM, Dimitri Liakhovitski
> <dimitri.liakhovitski at gmail.com> wrote:
>> Please help:
>> # I have a data frame x:
>> x <- data.frame(a = c(1:3, NA), b = c(NA, 2:4))
>> # I run a cross-tab keeping NAs, like this:
>> table(x[c("a", "b")], useNA = "ifany")
>> # I want to reproduce it using xtabs, but it ignores NAs:
>> xtabs(~ a + b, x)
>> # I can't figure out how to force xtabs to include NAs.
>> # All my attempts below fail to include NAs:
>> xtabs(~ a + b, x, na.action(na.pass))
>> xtabs(~ a + b, x, na.action = "na.pass")
>> xtabs(~ a + b, x, na.action(na.pass(x)))
>> xtabs(~ a + b, x, exclude = NULL)
>> Thank you for your hints!
>> Dimitri Liakhovitski
>> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
>> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
>> and provide commented, minimal, self-contained, reproducible code.
R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
and provide commented, minimal, self-contained, reproducible code.
More information about the R-help