【问题标题】:How do you use mutate_at with case_when for different columns to fill different values?如何使用 mutate_at 和 case_when 为不同的列填充不同的值?
【发布时间】:2021-03-19 00:20:19
【问题描述】:

我有一个包含多列的数据框 (demo_df),我正在尝试根据特定条件添加两个新列。如果满足条件,这两列将填充不同的值。我在 mutate_at 中使用 case_when 来改变 两个 变量。

  1. 查询文本
  2. 查询状态

我该怎么做?到目前为止,我有以下代码。

queries <- demo_df%>%
          mutate_at(vars(c(QueryText, QueryStatus)) = case_when(
          VISIT == "SCRN" & nles <=3 ~ {"Respond","High"},
          VISIT == "D1" & nles >3 ~ {"Ignore","Low"}))

【问题讨论】:

    标签: r dplyr tidyr data-manipulation


    【解决方案1】:

    您不能在一个case_when 语句中分配多个列。试试看:

    library(dplyr)
    
    queries <- demo_df %>%
      mutate(QueryText = case_when(
                      VISIT == "SCRN" & nles <=3 ~ "Respond"},
                      VISIT == "D1" & nles >3 ~ "Ignore"), 
             QueryStatus = case_when(QueryText == 'Respond' ~ 'High', 
                                     QueryText == 'Ignore' ~ 'Low'))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-06-12
      • 1970-01-01
      • 1970-01-01
      • 2019-03-14
      • 1970-01-01
      • 2014-08-17
      • 2021-06-26
      相关资源
      最近更新 更多