【问题标题】:Using results of case_when from first line and using the results to evaluate second condition使用第一行中 case_when 的结果并使用结果来评估第二个条件
【发布时间】:2019-05-17 22:50:11
【问题描述】:

我对 R 还很陌生,正在尝试清理数据。我正在使用 case_when 将 Yes、No 和 Unknown 分配给变量。我想分配相同的变量 No 和 Unknown,如果它在第一个语句中被分配为 Yes 并且其他语句为真或假。

这就是我所拥有的:

    ID col1  col2  
    1   Ball  a  
    2   NA    c   
    3   Bat   b  

这就是我想要达到的目标:

    ID col1  col2  x
    1   Ball  a   No
    2   NA    c   Yes
    3   Bat   b   Unknown
 mutate(x = case_when(
      is.na(col1) == TRUE ~ "Yes",
      !is.na(col1) == TRUE & (col2 %in% c("a", "b")|
      (col2 == "YES" & x == "Unknown" ) == TRUE ) ~ "No"),
TRUE ~ "Unknown"
))

基本上我想使用第一个 case_when 中 x 的结果并在第二行代码中使用它。如果 col1 为 NA,我基本上希望我的列 x 为“是”。如果 col1 没有丢失并且 (col2 %in% c("a", "b") or col1 == "Bat" and x = "Yes") 然后设置 x = "No"

有没有办法让它工作。任何帮助表示赞赏。

【问题讨论】:

  • 我无法理解您要执行的操作。如果您可以用一两行数据描述一个特定的示例以及您期望的输出,这将有所帮助。
  • 另外,测试一个测试是否为真是多余的。你可以写is.na(col1)而不是is.na(col1) == TRUE,因为第一部分已经等于TRUE。
  • @JonSpring 这是我的表的样子,请参阅上面有问题的更新。如果 col1 是 NA,我基本上希望我的列 x 是 Yes。如果 col1 没有丢失并且 (col2 %in% c("a", "b") or col1 == "Bat" and x = "Yes") 然后设置 x = "No" 。我的问题是如何在 case_when 条件的第二部分中使用第 1 部分中的 x = "Yes" 条件,我不知道该怎么做。

标签: r dplyr


【解决方案1】:

https://dplyr.tidyverse.org/reference/case_when.html

case_when 允许您列出一系列测试,并分配与第一个通过的测试相关联的值(即 TRUE)。

在大多数情况下,如果您仔细考虑测试的顺序,就可以获得您想要的结果。在这个问题中,你的指令、你的 cmets 和你的输出表似乎并不一致,这就很难回答了。在这里,我采用了您编辑的最后一个文本并将其用作逻辑的基础:

library(dplyr)
df %>%
  mutate(x = case_when(
    # First, test if col1 is NA -- if so, x will be "Yes" and we are done with the case_when.
    is.na(col1)  ~ "Yes",

    # For the second test, I'll rely on the text of your latest edit:
    #   "And if col1 is not missing and (col2 %in% c("a", "b") or 
    #    col1 == "Bat" and x = "Yes") then set x = "No"
    # (Note, this doesn't seem to be consistent with your output table...)

    # To get here means the prior test was false: col1 must have a non-NA value.
    col2 %in% c("a", "b") | col1 == "Bat"  ~ "No",

    # Otherwise, set to unknown
    TRUE  ~ "Unknown"
  ))

  ID col1 col2   x
1  1 Ball    a  No
2  2 <NA>    c Yes
3  3  Bat    b  No

【讨论】:

    猜你喜欢
    • 2019-01-07
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 2015-03-16
    • 1970-01-01
    • 1970-01-01
    • 2018-04-18
    • 1970-01-01
    相关资源
    最近更新 更多