R Language Creating vectors Creating named vectors

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

Named vector can be created in several ways. With c:

xc <- c('a' = 5, 'b' = 6, 'c' = 7, 'd' = 8)

which results in:

> xc
a b c d 
5 6 7 8

with list:

xl <- list('a' = 5, 'b' = 6, 'c' = 7, 'd' = 8)

which results in:

> xl
$a
[1] 5

$b
[1] 6

$c
[1] 7

$d
[1] 8

With the setNames function, two vectors of the same length can be used to create a named vector:

x <- 5:8
y <- letters[1:4]

xy <- setNames(x, y)

which results in a named integer vector:

> xy
a b c d 
5 6 7 8

As can be seen, this gives the same result as the c method.

You may also use the names function to get the same result:

xy <- 5:8
names(xy) <- letters[1:4]

With such a vector it is also possibly to select elements by name:

> xy["c"]
c 
7 

This feature makes it possible to use such a named vector as a look-up vector/table to match the values to values of another vector or column in dataframe. Considering the following dataframe:

mydf <- data.frame(let = c('c','a','b','d'))

> mydf
  let
1   c
2   a
3   b
4   d

Suppose you want to create a new variable in the mydf dataframe called num with the correct values from xy in the rows. Using the match function the appropriate values from xy can be selected:

mydf$num <- xy[match(mydf$let, names(xy))]

which results in:

> mydf
  let num
1   c   7
2   a   5
3   b   6
4   d   8


Got any R Language Question?