[R] which() in subset()

Rui Barradas ruipbarradas at sapo.pt
Fri Jul 13 18:32:36 CEST 2012


Hello,

To know why, just evaluate the condition, with 't1$' before 'version_1':

which(as.character(t1$version_1) %in% a) != 0
[1] TRUE TRUE


It allways evaluates to TRUE, therefore, subset() returns all rows.

See if this isn't simpler than both of your forms.

v2 <- subset(t1, version_1 %in% a)
v2
   id version_1
1  1     100-1
2  2     100-2

The trick is to use %in% when doing multiple comparisons. With the 
vector with length equal to the number of observations on the left hand 
side.

Hope this helps,

Rui Barradas

Em 13-07-2012 12:12, Charles Stangor escreveu:
> Why does the subset not work in the which() version below?
>
> Thank you
>
>
> v1 <- subset(t1,
>   version_1==as.character("100-1")
>   | version_1==as.character("100-2"))
>
> a<-c("100-1", "100-2")
> v1 <- subset(t1, which(a==as.character(version_1)) != 0)
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>



More information about the R-help mailing list