【问题标题】:dplyr error with mutate() when attempting to change variable value based on if_else condition尝试根据 if_else 条件更改变量值时 mutate() 出现 dplyr 错误
【发布时间】:2020-03-07 20:14:51
【问题描述】:

我正在尝试使用dplyr::mutate() 更改变量的值。如果在数据集中的 ID 列中找到来自字符向量的 ID,我想将“确定性”列的值从“不确定”更改为“可能”。如果不匹配,我想保留原始值。这是我当前尝试的一个代表:

library(dplyr)
library(magrittr)

data <- data.frame(
  ID = c("a100", "b100", "c100", "d100", "e100", "f100"),
  certainty = c("confirmed", "likely", "unsure", "likely", "unsure", "confirmed")
)

data %<>% as_tibble()

id_list <- c("c100", "e100")

data %<>%
  mutate(certainty = if_else(id_list %in% ID, "likely", certainty))

输出应如下所示:

 ID    certainty
  <fct> <fct>    
1 a100  confirmed
2 b100  likely   
3 c100  likely   
4 d100  likely   
5 e100  likely   
6 f100  confirmed

目前我收到此错误:

Error: `false` must be length 2 (length of `condition`) or one, not 6

我应该如何解决这个问题?

【问题讨论】:

    标签: r dplyr


    【解决方案1】:

    问题在于%in% 中的参数顺序。它返回id_list 的长度,如果我们使用id_list %in% ID,则为2。相反,它应该是另一种方式,即ID %in% id_list e..​​g

    1:3 %in% 1:2
    #[1]  TRUE  TRUE FALSE
    

    1:2 %in% 1:3
    #[1] TRUE TRUE
    

    这里是

    library(dplyr)
    data %>% 
          mutate(certainty = ifelse(ID %in% id_list, "likely", as.character(certainty)))
    
    # A tibble: 6 x 2
    #  ID    certainty
    #  <fct> <chr>    
    #1 a100  confirmed
    #2 b100  likely   
    #3 c100  likely   
    #4 d100  likely   
    #5 e100  likely   
    #6 f100  confirmed
    

    注意:certaintyfactor,所以需要转换为character 或添加likely 作为另一个级别(如果我们想坚持factor 类)


    也可以保留为factor

    library(forcats)
    data %>%
         mutate(certainty = fct_collapse(certainty,
                  likely = as.character(certainty)[ID %in% id_list]))\
    # A tibble: 6 x 2
    #  ID    certainty
    #  <fct> <fct>    
    #1 a100  confirmed
    #2 b100  likely   
    #3 c100  likely   
    #4 d100  likely   
    #5 e100  likely   
    #6 f100  confirmed
    

    【讨论】:

    • 这样一个简单的解决方案。在我的真实数据集中certainty 已经定义了多个级别。有没有办法将值更改为现有级别 likely 而无需转换为 character
    • @Sam 添加了另一个选项
    猜你喜欢
    • 1970-01-01
    • 2017-03-03
    • 2020-01-02
    • 2020-12-07
    • 2020-01-05
    • 2021-08-30
    • 1970-01-01
    • 2020-06-20
    • 1970-01-01
    相关资源
    最近更新 更多