[R] Ifelse stability problems?
peter dalgaard
pdalgd at gmail.com
Sun Dec 19 22:46:05 CET 2010
On Dec 19, 2010, at 15:01 , Peter Ehlers wrote:
> On 2010-12-19 03:50, Luca Meyer wrote:
>> I am just wondering why what I am showing below might occur.
>>
>> First I have an x data.frame:
>>
>>> str(x)
>> 'data.frame': 281 obs. of 2 variables:
>> $ x1 : Factor w/ 5 levels "A (50-67%)","B (10-20%)",..: 1 2 5 1 2 5 1 2 5 1 ...
>> $ x2 : num 33.8 60.2 6 76.8 13.8 9.4 76.9 8 15.1 78.1 ...
>>
>> I need to check that for each level of factor x1 the values of x2 are (approximately) contained within a given range. In such a case I will print "ok" a third variable, otherwise I will write "err"
>>
>> ifelse (x$x1 == "A (50-67%)",
>> x$check<-ifelse(x$x2<68&x$x2>49,"ok","xxxx"),
>> x$check<-x$check
>> )
>
> [...snip...]
>
>> Can anyone explain why this might occur?
>
> You have a bit of a logic problem in your ifelse;
> (look at your x$check after each of your ifelse()s);
> try it this way:
>
> x$check <- NA
> x$check <- ifelse (x$x1 == "A (50-67%)",
> ifelse(x$x2<68&x$x2>49,"ok","xxxx"),
> x$check
> )
>
Yes. The whole thing can be written much more concisely, though:
lw <- c(49,9,4,0,9)
up <- c(68,21,16,6,21)
x$check <- ifelse(x$x2 < up[x$x1] & x$x2 > lw[x$x1], "ok", "xxxx")
> etc.
>
> Peter Ehlers
>
>
>>
>> Thanks,
>> Luca
>>
>>
>> Luca Meyer
>> www.lucameyer.com
>> IBM SPSS Statistics release 19.0.0
>> R version 2.12.1 (2010-12-16)
>> Mac OS X 10.6.5 (10H574) - kernel Darwin 10.5.0
>>
>>
>>
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
--
Peter Dalgaard
Center for Statistics, Copenhagen Business School
Solbjerg Plads 3, 2000 Frederiksberg, Denmark
Phone: (+45)38153501
Email: pd.mes at cbs.dk Priv: PDalgd at gmail.com
More information about the R-help
mailing list