与多个向量一起使用case_when [英] Using case_when with multiple vectors

查看:215
本文介绍了与多个向量一起使用case_when的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 case_when 来基于两个单独的输入来修改/更改列。一种用于在RHS上创建LHS逻辑和相应输入值的模块。下面提供了一个示例。

I am trying to use case_when to modify/mutate a column based on two separate inputs. One that used to create the LHS logical and the respective input value on the RHS. An example is provided below.

library(dplyr)
library(purrr)
library(tibble)

df <- tibble(var = paste0(rep("var", 10), 1:10),
                 label = c("label1", "label2", rep(NA, 7), "label10"))

match_var <- paste0(rep("var", 7), 3:9)
new_labels <- paste0(rep("add_this_label", 7), 3:9)

df %>% 
  mutate(test = map2(match_var , new_labels,
                     ~case_when(
                       var == .x ~ .y,
                       TRUE ~ label
                     )
  ))

我认为问题是在 case_when 内,所有内容都被评估为表达式,但我不确定。一个人可以在 case_when 内手动键入所有7行,但是当向量 match_vars new_labels 很长-使得在 case_when 时手动键入不可行。

I think the issue is that within case_when everything is evaluated as expression but I'm not completely sure. One can manually type out all 7 lines within case_when but my application requires me to accomplish this when the vectors match_vars and new_labels are very long - making manual typing of case_when infeasible.

df %>% 
  mutate(label = case_when(
    var == match_var[1] ~ new_labels[1],
    var == match_var[2] ~ new_labels[2],
    var == match_var[3] ~ new_labels[3],
    var == match_var[4] ~ new_labels[4],
    var == match_var[5] ~ new_labels[5],
    var == match_var[6] ~ new_labels[6],
    var == match_var[7] ~ new_labels[7],
    TRUE ~ label
  ))

编辑:所需的结果可以可以使用 for 循环来完成,但是现在我想知道是否可以使用 case_when map2 _ * 函数?

EDIT: the desired result can be accomplished using a for loop but now I want to know if is this possible using case_when and map2_* function?

for (i in seq_along(match_var)) {
  df$label <- ifelse(df$var == match_var[i], new_labels[i], df$label)
}


推荐答案

我们创建一个命名向量,并使用该向量匹配'var'中的值,以便将NA元素更改为'new_labels'

We create a named vector and use that to match the the values in 'var' so as to change the NA elements to 'new_labels'

library(tibble)
library(dplyr)
df %>%
    mutate(label = case_when(is.na(label) ~ 
                       deframe(tibble(match_var, new_labels))[var], 
         TRUE ~ label))
# A tibble: 10 x 2
#   var   label          
#   <chr> <chr>          
# 1 var1  label1         
# 2 var2  label2         
# 3 var3  add_this_label3
# 4 var4  add_this_label4
# 5 var5  add_this_label5
# 6 var6  add_this_label6
# 7 var7  add_this_label7
# 8 var8  add_this_label8
# 9 var9  add_this_label9
#10 var10 label10        

注意:可以使用 setNames 创建命名向量,而不用使用 deframe 以及

NOTE: Instead of using deframe, the named vector can be created with setNames as well

这篇关于与多个向量一起使用case_when的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆