AnyCompiler

Indexing and Subsetting

x[i] with a positive i returns the element at that 1-based position. x[-i] does something most languages on this site don't have an equivalent for at all: it returns every element except position i — a negative index means "exclude", not "count from the end" the way Python's x[-1] does. A logical vector used as the index, like x[x > 25], keeps only the elements where the logical vector is TRUE — this is the selection mask pattern the previous lesson's x > 2 was setting up. Vectors can also carry names, settable with names(), and then be indexed by name as well as by position.

x <- c(10, 20, 30, 40, 50)
print(x[2])
print(x[-1])
print(x[x > 25])
names(x) <- c("a", "b", "c", "d", "e")
print(x["c"])
Output
[1] 20
[1] 20 30 40 50
[1] 30 40 50
 c 
30

x[-1] dropped only the first element (10) and kept the rest — it did not return the last element the way x[-1] would in Python. x[x > 25] used the vector's own values to decide which of its elements to keep, with no loop and no separate filter() call. And x["c"] looked a value up by the name you assigned it, printing both the name and the value, the same two-line shape named lookups always produce.

A real indexing error

Positive indices ("keep only these") and negative indices ("exclude these") are opposite instructions, and R refuses to guess which one you meant if you mix them in a single subscript. This is the real error R produces, captured from a real run:

x <- c(10, 20, 30)
print(x[c(-1, 2)])
Output
stderr
Error in x[c(-1, 2)] : only 0's may be mixed with negative subscripts
Calls: print
Execution halted

Unlike the warnings in the last two lessons, this one actually stops the script — R treats this specific combination as a genuine, unrecoverable mistake rather than something to work around silently. Next: strings — paste, sprintf, nchar, and substr.

Practice exercise

Given x <- c(1, 2, 3, 4, 5), print x with the first element excluded using a negative index, then print only the elements greater than 2 using a logical mask.