Lesson 3 of 8 · 8 min

Picking values out

Square brackets pick values out of a vector. R counts from 1:

x <- c(10, 20, 30, 40, 50)
x[1]           # 10
x[c(1, 3)]     # 10 30
x[2:4]         # 20 30 40
x[-1]          # everything except the first

By condition

A comparison gives a vector of TRUE/FALSE. Put it inside the brackets to keep only the TRUE positions:

x > 25              # FALSE FALSE TRUE TRUE TRUE
x[x > 25]           # 30 40 50
x[x > 15 & x < 45]  # 20 30 40   (& means "and", | means "or")
which(x > 25)       # 3 4 5      the positions

This is how you filter data in R, and it is fast because it is vectorised.

By name

Vectors can have names:

rain <- c(Jan = 160, Feb = 150, Mar = 100)
rain["Feb"]               # Feb 150
names(rain)               # "Jan" "Feb" "Mar"
names(rain)[which.max(rain)]   # "Jan"

which.max gives the position of the largest value; which.min of the smallest.

Your task

The starter has a named vector of daily sales.

  1. first_three: the first three days.
  2. good_days: only the days with sales above 100.
  3. best_day: the name of the day with the highest sales.
script.R
sales <- c(Mon = 120, Tue = 95, Wed = 140, Thu = 60, Fri = 180)

first_three <- NULL
good_days <- NULL
best_day <- NULL

print(good_days)

R 4.5 runs right here in your browser. The first run downloads about 25 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…