[1] 23.200 45.000 631.000 -273.000 0.000 48.371
[7] 100000.000 85.000 92.000 -236.000 8546.000 98774.000
[13] 0.000 0.000 1.000 3.000
(Section 2.1)
In R, a vector is a sequence of values. The values are called the elements of the vector.
Example:
3, 7, 10.1, -5
Another example:
“Ginger”, “Tina”, “Sita”, “Raj”
(They are not the same thing as vectors in math or physics.)
We won’t learn about non-atomic vectors until Chapter 9.
Vector Type
Any one of the six basic forms the elements in an atomic vector can take. The four types we will encounter the most are:
c()
FuncionThe c()
function “combines” values to make a vector.
double
is short for “double-precision.” It refers to a way that real numbers are stored in computers.
L
specifies that the value must be stored as a whole number.These are made up of strings.
[1] TRUE FALSE TRUE TRUE FALSE FALSE FALSE
In order to represent a logical value you use:
TRUE
to represent truth;FALSE
to represent falsity.What would happen if you entered this command?
Why?
… if you tried to represent falsity with the string "false"
?
newVector
is not a logical vector. Check it out:
c()
has to combine vectors of different typesThe rules for coercion are a bit complicated, but you’ll eventually know that:
character
beats double
,integer
,logical
.as.
-Functions[1] "3" "2.5" "-7.32" "0"
[1] 3 2 -7 0
[1] TRUE TRUE TRUE FALSE
Of course there is also an as.numeric()
function!
The NA
means that one of the heights was not recorded, or went missing somehow.
NA
If R cannot do a requested operation, it might return NA
:
R could figure out how to convert the first two strings to numbers, but did not know what to do with "four"
.
How many NA
s do you think this vector will have?
Try it! (You might be surprised.)
It’s really a numerical vector, of length 1.
Even NA
is just a vector of length 1
It’s a logical vector:
Even the type of a vector is a vector!
It’s a character vector, of length 1.
The elements of a vector can have names, if we like:
Name at the time of creation:
Name after creation:
R comes with two handy, predefined character vectors:
[1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" "p" "q" "r" "s"
[20] "t" "u" "v" "w" "x" "y" "z"
[1] "A" "B" "C" "D" "E" "F" "G" "H" "I" "J" "K" "L" "M" "N" "O" "P" "Q" "R" "S"
[20] "T" "U" "V" "W" "X" "Y" "Z"
We will make use of them from time to time.
length()
FunctionIt tells you how many elements the vector has.
What is the length of the vector LETTERS
?
Write an R command to get the length of LETTERS
.