Home > Enterprise >  How to find out how many numbers in my vector is lower than a given number
How to find out how many numbers in my vector is lower than a given number

Time:09-23

I want to find out how many numbers in my vector are lower than a given value. I came up with this code but get the following warning message. I've tried different things like comparing vectors of the same size etc. but nothing seems to work.

test.seq <- seq(from = 20000, to = 0, length.out = 100) 
n.lower <- matrix(0, nrow = 1, ncol = 1)
for(i in 1:100){
   if(test.seq < 10000){
      n.lower <- n.lower   1
   }
}

Warning message:
In if (test.seq < 1000) { :
  the condition has length > 1 and only the first element will be used

Thanks!

CodePudding user response:

A simple way to do it:

sum(test.seq < 10000)
[1] 50

If you want to use a loop:

n.lower <- 0

for(i in 1:100){
  if(test.seq[i] < 10000){
    n.lower <- n.lower   1
  }
}

n.lower
[1] 50

-- data

test.seq <- seq(from = 20000, to = 0, length.out = 100) 

CodePudding user response:

We could use length and which

length(which(test.seq < 10000))
[1] 50

or the for loop can also be written directly by on the logical vector as TRUE -> 1 and FALSE -> 0

for(i in 1:100) n.lower <- n.lower   (test.seq[i] < 10000)

-output

> n.lower
[1] 50
  • Related