问题
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?
Case1:
> 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
Case 2:
> b
[1] 4
> temp[1: 8]
[1] 1 2 3 4 5 6 7 8
> temp[1: b+b]
[1] 5 6 7 8
回答1:
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
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
回答2:
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.
来源:https://stackoverflow.com/questions/38335734/subsetting-r-with-dynamic-variables