I have a variable (Var) which stores 10000 values and is of integer nature.
I want to count, how many times 1000 or higher than 1000 numeric value occurs in this list.
Any one liner in R?
Thank you in advance.
Join Stack Overflow to learn, share knowledge, and build your career.
I have a variable (Var) which stores 10000 values and is of integer nature.
I want to count, how many times 1000 or higher than 1000 numeric value occurs in this list.
Any one liner in R?
Thank you in advance.
sum(Var >= 1000)
will do it, as long as Var
is a vector. If not, you'll need to tell R to find Var
inside whatever object contains it. Here is an example:
> set.seed(2)
> Var <- sample(900:1100, 10)
> Var
[1] 937 1040 1014 933 1085 1084 925 1061 990 1005
> Var >= 1000
[1] FALSE TRUE TRUE FALSE TRUE TRUE FALSE TRUE FALSE TRUE
> sum(Var >= 1000)
[1] 6
This uses the fact that TRUE
= 1 and FALSE
= 0.
sum(Var>=1000)
Suggest you read some of the intro R docs, this kind of thing crops up all the time. Also, what you have is hopefully not a 'list' but a 'vector'. If it is a 'list' then... ummm, unlist() it first.
mean(Var>=1000)
is a clever shorthand for sum(Var>=1000)/length(Var)
– Ben Bolker
Aug 23 '11 at 17:15
Try this:
sum(r >= 1000)
where r is a vector. This works because R automatically converts the booleans TRUE/FALSE to the values 1 and 0 when you try to sum a boolean vector.
It's also possible to use:
vec <- sample(1:10, 15, replace = TRUE)
table(vec > 2)
or
length(vec[vec>2])