R:使用 case_match() 和 char 数组重新编码值

问题描述 投票:0回答:1

在 dplyr 包中,recode()

 已被 
case_match()
 取代。有没有办法使用存储在 char 数组中的标签来使用 
case_match()
 重新编码值?

例如,使用

recode()

,我可以将标签存储在字符数组中(或从 CSV 文件中读取它们)并使用它们进行重新编码:

lbls <- c( 'male' = 'Man', 'female' = 'Woman' ) starwars %>% select( sex ) %>% mutate( sex = recode( sex, !!!lbls ) ) # A tibble: 87 × 1 # sex # <chr> # 1 Man # 2 none # 3 none # 4 Man # 5 Woman # ...
但是,由于 

case_match()

 需要双面公式 (
old_values ~ new_value
),所以这是行不通的。有没有办法在 
case_match()
 中也使用存储的值?

r dplyr recode
1个回答
0
投票
您可以创建要评估的规则列表。让我们以

tidyverse

的方式来做:

(rules <- glue::glue('"{lbl}" ~ "{val}"', lbl = names(lbls), val = lbls)) # "male" ~ "Man" # "female" ~ "Woman"
然后您可以使用 

rlang::parse_exprs()

 来评估:

starwars |> select(sex) |> mutate( sex = case_match( sex, !!!rlang::parse_exprs(rules), .default = sex ) ) # # A tibble: 87 × 1 # sex # <chr> # 1 Man # 2 none # 3 none # 4 Man # 5 Woman # 6 Man # 7 Woman # 8 none # 9 Man # 10 Man # # ℹ 77 more rows # # ℹ Use `print(n = ...)` to see more rows
    
© www.soinside.com 2019 - 2024. All rights reserved.