[R] Question about subset

Sebastien Bihorel @eb@@t|en@b|hore| @end|ng |rom cogn|gencorp@com
Tue Apr 10 13:10:30 CEST 2018


Thanks.

That works great!

> df <- data.frame(x=c(1,1,NA,NA,2), y=c('a','a','a','b','b'), z=c(TRUE,FALSE,TRUE,FALSE,TRUE))
> cond1 <- 'x==1'
> cond2 <- 'x==1 & z'
> df
   x y     z
1  1 a  TRUE
2  1 a FALSE
3 NA a  TRUE
4 NA b FALSE
5  2 b  TRUE
> subset(df, subset = ifelse(is.na(eval(parse(text=cond1))), TRUE, eval(parse(text=cond1))))
   x y     z
1  1 a  TRUE
2  1 a FALSE
3 NA a  TRUE
4 NA b FALSE
> subset(df, subset = ifelse(is.na(eval(parse(text=cond2))), TRUE, eval(parse(text=cond2))))
   x y    z
1  1 a TRUE
3 NA a TRUE


----- Original Message -----
From: "S Ellison" <S.Ellison using LGCGroup.com>
To: "Sebastien Bihorel" <sebastien.bihorel using cognigencorp.com>
Sent: Monday, April 9, 2018 8:31:55 AM
Subject: RE: Question about subset

> Before I try to re-invent the wheel, I would like to know if one of the base or
> recommended packages would contain a variant of the subset function that
> would consider missing values as true.

The subset argument to subset is something that evaluates to logical - a vector of True or False. 
If you wanted to treat missing values _in that_ as TRUE, wrap it in an ifelse:

ifelse(is.na(condition), TRUE, condition)

where condition can be a logical or an expression evaluating to logical.

S Ellison



*******************************************************************
This email and any attachments are confidential. Any use...{{dropped:8}}




More information about the R-help mailing list