I have a dataframe with two columns, which are the initials of a name (col1) and an assigned value to it (col2)
dat <- data.frame(col1 = c("A","B","C"), col2 = c(4,5,6)) %>% as_tibble()
And i have a named vector, whose names are the initials and the values are the full names
nam <- c("A" = "Andrew", "B" = "Bob", "C" = "Charles")
Given that i would like to have a third name with these names using dplyr's mutate once i am working in a pipe. The dataset should be something like this by the end.
dat2 <- data.frame(col1 = c("A","B","C"), col2 = c(4,5,6), col3 = c("Andrew","Bob","Charles")) %>% as_tibble()
How can i achieve this?
CodePudding user response:
A possible solution:
library(dplyr)
dat %>%
mutate(col3 = nam[match(col1, names(nam))])
#> # A tibble: 3 × 3
#> col1 col2 col3
#> <chr> <dbl> <chr>
#> 1 A 4 Andrew
#> 2 B 5 Bob
#> 3 C 6 Charles
CodePudding user response:
You could use recode()
and pass a named character vector for unquote splicing with !!!
.
dat %>%
mutate(col3 = recode(col1, !!!nam))
# # A tibble: 3 × 3
# col1 col2 col3
# <chr> <dbl> <chr>
# 1 A 4 Andrew
# 2 B 5 Bob
# 3 C 6 Charles
CodePudding user response:
You can use the following code:
library(tibble)
dat <- data.frame(col1 = c("A","B","C"), col2 = c(4,5,6)) %>% as_tibble()
nam <- c("A" = "Andrew", "B" = "Bob", "C" = "Charles")
library(dplyr)
dat %>%
mutate(col3 = nam[as.character(col1)])
#> # A tibble: 3 × 3
#> col1 col2 col3
#> <chr> <dbl> <chr>
#> 1 A 4 Andrew
#> 2 B 5 Bob
#> 3 C 6 Charles
Created on 2022-07-13 by the reprex package (v2.0.1)