[英]Use dplyr mutate when the values of a column are the names of a vector
I have a dataframe with two columns, which are the initials of a name (col1) and an assigned value to it (col2)我有一个包含两列的数据框,它们是名称的首字母(col1)和为其分配的值(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.鉴于一旦我在管道中工作,我希望使用 dplyr 的 mutate 来使用这些名称的第三个名称。 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?我怎样才能做到这一点?
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
You could use recode()
and pass a named character vector for unquote splicing with !!!
您可以使用
recode()
并传递一个命名字符向量以使用!!!
取消引用拼接. .
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
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)由reprex 包(v2.0.1) 于 2022-07-13 创建
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.