Fortranner
Fortranner

Reputation: 2605

Slicing an R vector

For the code

nobs <- 10
nskip <- 3
x <- 1:nobs    
print(x)    
print(x[4:10])    
print(x[nskip+1:nobs])

the output is

[1]  1  2  3  4  5  6  7  8  9 10    
[1]  4  5  6  7  8  9 10   
[1]  4  5  6  7  8  9 10 NA NA NA

I don't understand why the last two lines of output differ -- why are there NA's?

Upvotes: 3

Views: 6188

Answers (3)

Niru
Niru

Reputation: 11

Another method is to use seq, which also allows more generic slicing with a jump value.

nobs  <- 12
nskip <- 3
njump <- 4
x     <- 1:nobs    
print(x[seq(nskip+1, nobs, 1)])
print(x[seq(nskip+1, nobs, njump)])

Output

[1]  4  5  6  7  8  9 10 11 12
[1]  4  8 12

Learning the operator precedence is always helpful!

https://stat.ethz.ch/R-manual/R-devel/library/base/html/Syntax.html

Upvotes: 0

Ciar&#225;n Tobin
Ciar&#225;n Tobin

Reputation: 7536

You are missing some parentheses. Look at the sequence you get when you do this

nskip + 1:nobs
# 4  5  6  7  8  9 10 11 12 13

It's generating the sequence from 1 to nobs and then adding nskip to each element. You are getting NAs because elements 11 to 13 do not exist within x.

You need to include parentheses to produce the correct sequence.

print(x[(nskip+1):nobs])

Now, the part between the parentheses gets evaluated first, so that the sequence is then generated between (nskip + 1) and nobs.

Upvotes: 1

Tommy Levi
Tommy Levi

Reputation: 781

Put parentheses around (nskip+1), the order of operations is off as you have it.

Upvotes: 5

Related Questions