Reputation: 105
I'm trying to cut a character vector a little and stumbled upon a small problem: I'd like to exclude all elements before a certain position i + 1 and I'd also like to exclude its last element. Now the weird thing: If I use i + 1 for indexing, it produces NAs at the end of the new vector. If I use a number instead it works as intended (see example):
# create character vector
nl <- c(letters[1:10], "excl")
# this produces NAs:
i = 5
nl[i+1:length(nl)-1]
# this works fine
nl[6:length(nl)-1]
Can anyone explain why this happens? I couldn't find an explanation on the internet and it doesn't really make sense to me.
Thanks in advance!
Upvotes: 1
Views: 15
Reputation: 887168
It is because of operator precedence, use ()
to block
nl[(i+1):length(nl)-1]
#[1] "e" "f" "g" "h" "i" "j
If the range should include the subtraction as well
nl[(i+1):(length(nl) - 1)]
#[1] "f" "g" "h" "i" "j"
Upvotes: 1