Search code examples
rmatrixvectorindexingoperation

How can we do operations inside indexing operations in R?


For example, let's imagine following vector in R:

a <- 1:8; k <- 2

What I would like to do is getting for example all elements between 2k and 3k, namely:

interesting_elements <- a[2k:3k]
Erreur : unexpected symbol in "test[2k"
interesting_elements <- a[(2k):(3k)]
Erreur : unexpected symbol in "test[2k"

Unfortunately, indexing vectors in such a way in R does not work, and the only way I can do such an operation seems to create a specific variable k' storing result of 2k, and another k'' storing result of 3k.

Is there another way, without creating each time a new variable, for doing operations when indexing?


Solution

  • R does not interpret 2k as scalar multiplication as with other languages. You need to use explicit arithmetic operators.

    If you are trying to access the 4 to 6 elements of a then you need to use * and parentheses:

    a[(2*k):(3*k)]
    [1] 4 5 6
    

    If you leave off the parentheses then the sequence will evaluate first then the multiplication:

    2*k:3*k
    [1]  8 12
    

    Is the same as

    (k:3)*2*k
    [1]  8 12