[英]use dplyr mutate to create new columns based on a vector of column names
[英]Use dplyr mutate when the values of a column are the names of a vector
我有一個包含兩列的數據框,它們是名稱的首字母(col1)和為其分配的值(col2)
dat <- data.frame(col1 = c("A","B","C"), col2 = c(4,5,6)) %>% as_tibble()
我有一個命名向量,其名稱是首字母,值是全名
nam <- c("A" = "Andrew", "B" = "Bob", "C" = "Charles")
鑒於一旦我在管道中工作,我希望使用 dplyr 的 mutate 來使用這些名稱的第三個名稱。 數據集最終應該是這樣的。
dat2 <- data.frame(col1 = c("A","B","C"), col2 = c(4,5,6), col3 = c("Andrew","Bob","Charles")) %>% as_tibble()
我怎樣才能做到這一點?
一個可能的解決方案:
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
您可以使用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
您可以使用以下代碼:
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
由reprex 包(v2.0.1) 於 2022-07-13 創建
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.