15.12 Changing the Names of Items in a Character Vector

15.12.1 Problem

You want to change the names of items in a character vector.

15.12.2 Solution

Use recode() from the dplyr package:

library(dplyr)

sizes <- c("small", "large", "large", "small", "medium")
sizes
#> [1] "small"  "large"  "large"  "small"  "medium"

# With recode(), pass it a named vector with the mappings
recode(sizes, small = "S", medium = "M", large = "L")
#> [1] "S" "L" "L" "S" "M"

# Can also use quotes -- useful if there are spaces or other strange characters
recode(sizes, "small" = "S", "medium" = "M", "large" = "L")
#> [1] "S" "L" "L" "S" "M"

15.12.3 Discussion

If you want to use two vectors, one with the original levels and one with the new ones, use do.call() with fct_recode().

old <- c("small", "medium", "large")
new <- c("S", "M", "L")
# Create a named vector that has the mappings between old and new
mappings <- setNames(new, old)
mappings
#>  small medium  large 
#>    "S"    "M"    "L"

# Create a list of the arguments to pass to fct_recode
args <- c(list(sizes), mappings)
# Look at the structure of the list
str(args)
#> List of 4
#>  $       : chr [1:5] "small" "large" "large" "small" ...
#>  $ small : chr "S"
#>  $ medium: chr "M"
#>  $ large : chr "L"
# Use do.call to call fct_recode with the arguments
do.call(recode, args)
#> [1] "S" "L" "L" "S" "M"

Or, more concisely, we can do all of that in one go:

do.call(
  recode,
  c(list(sizes), setNames(c("S", "M", "L"), c("small", "medium", "large")))
)
#> [1] "S" "L" "L" "S" "M"

Note that for recode(), the name and value of the arguments is reversed, compared to the fct_recode() function from the forcats package. With recode(), you would use small="S", whereas for fct_recode(), you would use S="small".

A more traditional R method is to use square-bracket indexing to select the items and rename them:

sizes <- c("small", "large", "large", "small", "medium")
sizes[sizes == "small"]  <- "S"
sizes[sizes == "medium"] <- "M"
sizes[sizes == "large"]  <- "L"
sizes
#> [1] "S" "L" "L" "S" "M"

15.12.4 See Also

If, instead of a character vector, you have a factor with levels to rename, see Recipe 15.10.