Vectors
Suppose we’d like to compute how much sales tax we’re paying for some of our purchases.
Suppose we’d like to compute how much sales tax we’re paying for some of our purchases.
Suppose we’d like to compute how much sales tax we’re paying for some of our purchases.
Suppose we’d like to compute how much sales tax we’re paying for some of our purchases.
sales_tax <- 0.1025 # in Berkeley today
boba <- 7.0
books <- 54.50
food <- 24.75
boba_tax <- boba * sales_tax
books_tax <- books * sales_tax
food_tax <- food * sales_tax
sum(boba_tax, books_tax, food_tax)
[1] 8.840625
Very cumbersome…
Boba Cost
*
Tax Rate
=
Taxes
Book Cost
*
Tax Rate
=
Taxes
Food Cost
*
Tax Rate
=
Taxes
Costs
*
Tax Rate
=
Taxes
… where Costs contains all individual purchase costs, and Taxes contains all individual taxes.
For this, R provides vectors.
A contiguous array of 1 or more objects, where all objects are the same type.
Our values are ultimately bits in our computer. How does our program know how to interpret these bits?
By assigning a type to the value!
We may wants the bits to be interpreted as
… or something else.
To make sense of the bits…
Programming languages are responsible for keeping track of the types assigned to each variable.
R is dynamically typed, which means we’re free to modify the type of a variable.
Note that R infers the variable’s type for us (in C and Java we’d need to write int x = 7
1).
R only has a few types you should be aware of for this class.
TRUE
/T
or FALSE
/F
7L
, -5L
, 0L
)15.4
, -8.3211
, 8.0
)"Hello, World!"
, "X"
)Use the function typeof
to get the type of a variable or literal1.
Casting is the act of modifying the type of a value.
Casting is the act of modifying the type of a value.
Casts you ask R to make explicitly are called explicit casts. Use the as.<type>
functions for this.
x
?as.<type>(x)
returns a new value with the specified type.
[1] "double"
[1] "logical"
[1] "double"
A contiguous array of 1 or more objects, where all objects are the same type.
A contiguous array of 1 or more objects, where all objects are the same type.
Use <vector>[N]
to access the \(Nth\) element of a vector.
[1] 1
[1] "Dwinelle"
[1] TRUE FALSE FALSE
R is not 0-indexed like most programming languages.
We can apply operations to vectors directly, causing the operation to be done to all its elements (vectorization).
Recall our taxes code.
[1] 8.840625
Great! But we’ve lost information. What do the values in purchases
represent?
We can associate a name with each value in a vector.
We can associate a name with each value in a vector.
Access is possible with names, <vector>[<element-name>]
.
The c
function can concatenate vectors (flatten them).
Want a vector of \(N\) identical values? Use rep
!
Want a sequence of values from \(A\) to \(B\) by increments of \(I\)? Use seq
!