typestar

Vectors and indexing in R

The vector is R's fundamental unit; everything indexes it.

temps <- c(18.2, 21.5, 19.8, 23.1, 17.4)
names(temps) <- c("mon", "tue", "wed", "thu", "fri")

first <- temps[1]
midweek <- temps[2:4]
warm <- temps[temps > 19]
without_friday <- temps[-5]

by_name <- temps["wed"]
n <- length(temps)

How it works

  1. c() builds a vector; names() labels its elements.
  2. Indexing takes positions, ranges, or a logical mask.
  3. A negative index drops that element instead.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
232
Tokens
77
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 58 seconds.

Type this snippet

Step 1 of 4 in Vectors & types, step 1 of 20 in Language basics.

Next →