Arguments for a subset within a function in a column R with greater or equal
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 multiply this data to select only cases with "x" between 1 and 3, I can do:
s1<- subset(data, x>=1 & x<=3)
and get the 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 got 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 enters a range of values from which she wants to see the average calculated over the "y" variable. I would prefer if they can use the ":" operator to pass this argument to a subset function inside my function, but I don't know why the subset with ":" is giving me different results.
I would be grateful for any suggestions on this matter.
source to share
You can use %in%
instead==
subset(data, x %in% 1:3)
In general, if we compare two vectors of unequal sizes, will be used %in%
. There are times when we can use recycling (it can also fail) if one of the vectors is twice as long as the other. Some examples with some description here .
source to share