Values and Vectors
Indexing
Picking Positions
R indexes vectors starting at 1. Bracket indexing and helper functions select the pieces a script needs.
Program
Play the script to see the first and last city selected from one vector.
indexing.R
Replay: real traced execution (multi-file project)
cities <- c("Paris", "Lima", "Cairo")
first <- cities[1]
last <- tail(cities, 1)
label <- paste(first, "to", last)
cat(label, "\n", sep = "")
cities ← Paris, Lima, Cairo
1cities <- c("Paris", "Lima", "Cairo")2first <- cities[1]values this stepParis, Lima, Cairocitiesfirst ← Paris
1cities <- c("Paris", "Lima", "Cairo")2first <- cities[1]3last <- tail(cities, 1)values this stepParisfirstPariscities[1]last ← Cairo
2first <- cities[1]3last <- tail(cities, 1)4label <- paste(first, "to", last)values this stepCairolastParis, Lima, Cairocitieslabel ← Paris to Cairo
3last <- tail(cities, 1)4label <- paste(first, "to", last)5cat(label, "\n", sep = "")values this stepParis to CairolabelParisfirstCairolastcat(label, " ", sep = "")
4label <- paste(first, "to", last)5cat(label, "\n", sep = "")outputParis to Cairovalues this stepParis to Cairolabel
Pick First and Last
citiesstoresParis,Lima, andCairo.cities[1]selectsParis.tail(cities, 1)selectsCairo.paste(first, "to", last)buildsParis to Cairo. | Position | City | Used as | | --- | --- | --- | |1|Paris| first | |2|Lima| neither | |3|Cairo| last |
one-based index
`cities[1]` selects the first element, not the zeroth.
tail
`tail(cities, 1)` selects the final element.
character vector
A character vector stores text values in order.
Exercise: indexing.R
Pick the first and last city from a vector and print a route label