14404

# Subsetting R with dynamic variables [duplicate]

<div class="question-status question-originals-of-duplicate">

<li> Brackets make a vector different. How exactly is vector expression evaluated? <span class="question-originals-answer-count"> 3 answers </span> </li> </ul>

I have the below example code. I have a dataframe ts which has 16 rows. when I subset with actual numbers it works fine but when I subset with calculated numbers why is my code behaving weirdly ?

Can anyone please explain me what's wrong in this?

<strong>Case1:</strong>

```> a [1] 12 > c [1] 16 > ts\$trend[13:16] [1] 21.36926 21.48654 21.60383 21.72111 > ts\$trend[a+1:c] [1] 21.36926 21.48654 21.60383 21.72111 NA NA NA NA NA NA NA NA [13] NA NA NA NA ```

<strong>Case 2:</strong>

```> b [1] 4 > temp[1: 8] [1] 1 2 3 4 5 6 7 8 > temp[1: b+b] [1] 5 6 7 8 ```

This is a case of operator precedence. It can be avoided by using brackets

```temp[1:(b+b)] #[1] 1 2 3 4 5 6 7 8 ``` <hr>

If we check the problem in OP's code

```1:b #[1] 1 2 3 4 (1:b) + b #[1] 5 6 7 8 ```

So, the operator precedence happens here by evaluating 1:b followed by adding the b.

This is well described in `?Syntax`

:: ::: access variables in a namespace \$ @ component / slot extraction [ [[ indexing ^ exponentiation (right to left) - + unary minus and plus : sequence operator %any% special operators (including %% and %/%) * / multiply, divide + - (binary) add, subtract < > <= >= == != ordering and comparison ! negation & && and | || or ~ as in formulae -> ->> rightwards assignment <- <<- assignment (right to left) = assignment (right to left) ? help (unary and binary)

### data

```temp <- 1:10 b <- 4 ```

R doesn't care about they way you space expressions. Things are evaluated according to a strict precedence scheme. Things in parentheses are done first. So:

```> 1: b+b [1] 5 6 7 8 ```

because addition has lower precedence than ":". The `1:b` is evaluated first, and then `b` is added. So you get:

```> (1:b)+b [1] 5 6 7 8 ```

If you want the alternative, parenthesise things:

```> 1:(b+b) [1] 1 2 3 4 5 6 7 8 ```

I'd suggest you also parenthesise `(1+b):b` if that is ever what you want - the brackets make no difference but they aid readability for anyone who forgets the precedence rules.