<- list("a", 3, NA, NaN, 0/0)
myList <- c("a", 3, NA, NaN, 0/0) myVect
Lists vs vectors
We need to point out some nuances that will get you at the unlikeliest of times related to the difference between lists and vectors—you should always be aware that a vector’s terms must all have the same type while a list’s terms can all be of different types.
Let’s walk through an example and see how this pops up. We are going to start by defining myList
and myVect
using the standard list- and vector-creation functions:
Let’s check that their types are as we would expect:
is.list(myList)
[1] TRUE
is.vector(myVect)
[1] TRUE
Yep. Looking good. Now let’s print the values of myList
. (And, yes, we’re using some R programming that you haven’t seen yet, but we think you can hang with us at this point.)
for (item in myList) print(item)
[1] "a"
[1] 3
[1] NA
[1] NaN
[1] NaN
Referring back to where we defined myList
above, we can see that these five values are just about the same as what we entered. The only change is that 0/0
is represented as NaN
because…well, because it is not a number. We consider this a win.
Now let’s print out the type of each of those items:
for (item in myList) print(typeof(item))
[1] "character"
[1] "double"
[1] "logical"
[1] "double"
[1] "double"
Again, all looks good.
Let’s do the same for the vector myVect
. Here are the items it contains:
for (item in myVect) print(item)
[1] "a"
[1] "3"
[1] NA
[1] "NaN"
[1] "NaN"
for (item in myVect) print(typeof(item))
[1] "character"
[1] "character"
[1] "character"
[1] "character"
[1] "character"
Wait! This doesn’t seem to be what we want. Everything has been coerced to a string! What’s going on? This doesn’t make sense!
Well, yes, it does. R did what we told it to do. It just did it without really explaining itself to us.
When we defined myVect
, we asked R to create a vector made up of a character, a double, a NA
, and a couple of NaN
s. Well, a vector can only have data of one type in it. The only way to do that with this data is to coerce everything into strings! So, that’s what it did.
We can see the result here:
typeof(myVect)
[1] "character"
The vector is of type character
, meaning that every element of myVect
has been coerced into a string.
The lesson: create vectors with care! Be sure that every element in it is of the same type…or you will get a surprise somewhere down the line.