Arguments for Subset within a function in R colon v. greater or equal to

459 views Asked by At

Suppose I have the following data.

x<- c(1,2, 3,4,5,1,3,8,2)
y<- c(4,2, 5,6,7,6,7,8,9)
data<-cbind(x,y)

    x   y
1   1   4
2   2   2
3   3   5
4   4   6
5   5   7
6   1   6
7   3   7
8   8   8
9   2   9  

Now, if I subset this data to select only the observations with "x" between 1 and 3 I can do:

s1<- subset(data, x>=1 & x<=3)

and obtain my desired output:

    x   y
1   1   4
2   2   2
3   3   5
4   1   6
5   3   7
6   2   9

However, if I subset using the colon operator I obtained a different result:

s2<- subset(data, x==1:3)

    x   y
1   1   4
2   2   2
3   3   5

This time it only includes the first observation in which "x" was 1,2, or 3. Why? I would like to use the ":" operator because I am writing a function so the user would input a range of values from which she wants to see an average calculated over the "y" variable. I would prefer if they can use ":" operator to pass this argument to the subset function inside my function but I don't know why subsetting with ":" gives me different results.

I'd appreciate any suggestions on this regard.

1

There are 1 answers

6
akrun On BEST ANSWER

You can use %in% instead of ==

 subset(data, x %in% 1:3)

In general, if we are comparing two vectors of unequal sizes, %in% would be used. There are cases where we can take advantage of the recycling (it can fail too) if the length of one of the vector is double that of the second. Some examples with some description is here.