Reputation: 5522
v <- c(1,2,3,4,5,6)
And I mention max=4,min=2
So, I want to know how many values fall outside this range.
I can do this (v < 2 & v > 4)
But not sure how to do the count...
After that I will simply create a percentage with respect to total number of values (here 6).
Upvotes: 3
Views: 3311
Reputation: 5586
You can create and sum a logical vector. TRUE
elements count as 1 and FALSE
as 0, so this will give you the number of elements matching a particular condition.
v <- c(1, 2, 3, 4, 5, 6)
sum(v < 2 | v > 4)
The latter returns 3 because there are three values less than 2 or greater than 4. The comparisons are vectorized, so v < 2
tests whether each element of v
in turn is less than 2. The OR operator is given by |
in R.
To get the proportion of values beyond the range, you can divide the sum by the length of the vector, or alternatively use mean()
, since the mean is the sum divided by the length.
mean(v < 2 | v > 4)
Upvotes: 3
Reputation: 17611
You can simply do:
sum(v < 2 | v > 4) / length(v)
[1] 0.5
You want to use |
instead of &
because no number will be both less than 2 and greater than 4.
Upvotes: 2