Counting the number of times a value occurs

I have a variable (Var) that stores 10,000 values ​​and has a whole nature.

I want to count how many times 1000 or more than 1000 numerical values ​​in this list.

Any one liner in R?

Thanks in advance.

+7
source share
5 answers

sum(Var >= 1000) will do this while Var is a vector. If not, you need to specify R to find Var inside any object containing 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 exploits the fact that TRUE = 1 and FALSE = 0.

+11
source
 sum(Var>=1000) 

Suggest that you read some of the built-in R-documents, such things appear all the time. In addition, you have, I hope, not a "list", but a "vector". If it is a "list", then ... ummm, unlist () first.

+10
source

Try the following:

  sum(r >= 1000) 

where r is a vector. This works because R automatically converts the boolean values ​​TRUE / FALSE to the values ​​1 and 0 when you try to sum the boolean vector.

+4
source

may not be as effective but I like

 > length(which(Var>=1000)) 
+3
source

You can also use:

 vec <- sample(1:10, 15, replace = TRUE) table(vec > 2) 

or

 length(vec[vec>2]) 
0
source

All Articles