R, lesson 7
R was designed for data, so its main collection, the vector, is everywhere. A vector is an
ordered sequence of values that all share one type. You build one with c(), short for
"combine":
Square brackets pick elements. Positions start at 1:
You can also assign through an index: scores[2] <- 99. To add to the end, combine:
scores <- c(scores, 64).
Arithmetic and comparisons apply to every element at once. No loop needed:
That logical vector is a filter. Put it inside the brackets to keep only the TRUE positions:
Summary functions take a whole vector: sum(), mean(), min(), max(), ,
(add to reverse) and . tells you the
of the largest value, which is useful for finding scored it.
2 exercises to try what you just read.
range()sort()decreasing = TRUErev()which.max(scores)Give elements names and you can look them up by name, much like a dictionary:
x %in% y checks whether each value of x appears in y, which is the safe way to test for a
key before using it.
A vector holds one type. A list can hold anything, including other vectors, each with an optional name:
Use $ or [[ ]] to get an element out of a list. Single brackets, pet["age"], return a
smaller list, not the value, which is a common surprise.
Now the recipe from lesson 3 makes sense: strsplit() returns a list (one element per input
string), and [[1]] takes out the first element, a character vector of words.
[, [[ and $The input is one line of exam scores (whole numbers) separated by spaces. Print four lines: the number of scores, the average with 1 decimal, the highest score, and how many scores are 50 or more.
Sample input:
Sample output:
The starter has a named vector of prices per item. Each input line is an order in the form
item quantity. For each line, print item x quantity = cost with the cost to 2 decimals. If
the item is not in prices, print item: not sold instead. At the end print the total of the
items that were sold, with 2 decimals.
Sample input:
Sample output:
scores <- c(72, 95, 58, 81)
names_v <- c("Ada", "Ben", "Cleo")
length(scores) # 4scores[1] # 72
scores[c(1, 3)] # 72 58
scores[-1] # everything except the first: 95 58 81
scores[length(scores)] # the last one: 81scores + 5 # 77 100 63 86
scores >= 60 # TRUE TRUE FALSE TRUEscores[scores >= 60] # 72 95 81
sum(scores >= 60) # 3, because TRUE counts as 1prices <- c(tea = 2.2, coffee = 2.8, juice = 3.5)
prices["coffee"] # coffee 2.8 (keeps the name)
prices[["coffee"]] # 2.8 (just the value)
names(prices) # "tea" "coffee" "juice"
"milk" %in% names(prices) # FALSE
prices["milk"] <- 1.5 # add a new entrypet <- list(name = "Biscuit", age = 3, tags = c("friendly", "loud"))
pet$name # "Biscuit"
pet[["age"]] # 3
pet$tags[2] # "loud"
pet$owner <- "Sam" # add a field72 95 41 58 88Count: 5
Average: 70.8
Best: 95
Passed: 4apple 4
kiwi 2
mango 1apple x 4 = 2.00
kiwi: not sold
mango x 1 = 1.75
Total: 3.75