Size of a predefined range within a vector

Asked

Viewed 161 times

2

I wonder how I can calculate the amount of elements I have in a predefined range, within a vector.

For example: Let’s say I have a size 10 vector. My intention for example is to want to know how many elements have between the second element of my vector until the sixth element of my vector.

vetor=c(1,2,3,4,5,6,7,8,9,10)

I want to know how many numbers I have between the second element of my vector(vetor[2]) and the sixth element (vetor[6]). That in this case there are 5 elements.

Note: In this case I want the second and sixth element to be part of the count.

  • 2

    If I understand correctly you just want to count the number of elements between two positions n1 and n2. In this case, it’s just a mathematical matter, independent of any language. Just do the math: numero = n2 - n1 + 1.

1 answer

2


Well, as Luiz Vieira said, in this case you can simply calculate.

Anyway, just to not leave without an answer, you can subset your vector first vetor[2:6] and then count how many elements the vector subset has using length:

vetor=c(1,2,3,4,5,6,7,8,9,10) 
length(vetor[2:6])
[1] 5
  • 1

    Thank you so much for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.