Back to basics: Named Vectors
In the previous newsletter I reviewed R vectors - which are like standard programming arrays - sort of - but not really. They are more like one-dimensional arrays, but that's for a later newsletter...
Before we move on to other R data structures, I wanted to put another R feature into context with other programming languages. In this case, let's compare R's named vectors with python dictionaries - which are also described as associative arrays. All of these have key-value structures. You ask for the key - and get the value.
# here's a python dictionary...
ImAKeyValue = {'first': "twas", 'second': "brillig"}
# here's a named vector in R
ImAKeyValue <- c('first' = "twas",'second' = "brillig")
Both of these allow me to access a value by name. Here's how that looks in R...
> ImAKeyValue["first"]
first
"twas"
If you want multiple values, use c()...like this...
ImAKeyValue[c("first","second")]
first second
"twas" "brillig"
You'll often see named vectors in R defined in two steps. Here's an example...
ImAKeyValue <- c("twas","brillig")
names(ImAKeyValue) <- c("first","second")
Both forms produce the same result.
By the way...
I've produced a "quick" reference to matrix math functions in R. You can see it here.