【问题标题】:Ifelse condition retaining NA's [closed]Ifelse条件保留NA的[关闭]
【发布时间】:2020-10-24 20:09:20
【问题描述】:

我必须对两列应用条件才能获得新列 使用 1 和 0,我希望 column1 中的 NA 保留为 NA 新列。我如何在 R 中做到这一点?

这是代码

df$newcolumn <- ifelse(((df$col1 %in% ("eat")) |
      (df$col2 %in% ("yes"))), 1,  0)

【问题讨论】:

  • 如果您包含一个简单的reproducible example,其中包含可用于测试和验证可能解决方案的示例输入和所需输出,则更容易为您提供帮助。

标签: r if-statement na


【解决方案1】:

试试这个。要保留 NAs,请添加另一个 ifelse,它会检查 col1 中的 NAs 并保留它们。

df <- structure(list(col1 = c(
  NA, "drink", "drink", "drink", "eat",
  "eat", "eat", NA, "eat", "drink"
), col2 = c(
  "yes", "yes", "no",
  "no", "yes", "yes", "yes", "yes", "no", "yes"
), newcolumn = c(
  NA,
  "1", "0", "0", "1", "1", "1", NA, "1", "1"
)), row.names = c(
  NA,
  -10L
), class = "data.frame")

df$newcolumn <- ifelse(is.na(df$col1), df$col1, ifelse(df$col1 %in% ("eat") | df$col2 %in% ("yes"), 1, 0))
df
#>     col1 col2 newcolumn
#> 1   <NA>  yes      <NA>
#> 2  drink  yes         1
#> 3  drink   no         0
#> 4  drink   no         0
#> 5    eat  yes         1
#> 6    eat  yes         1
#> 7    eat  yes         1
#> 8   <NA>  yes      <NA>
#> 9    eat   no         1
#> 10 drink  yes         1

【讨论】:

  • 这使得“yes”和“drink”为0,我希望它为1。
  • ifelse("drink" %in% ("eat") | "yes" %in% ("yes"), 1, 0) 在我的机器上给了我一个 1。
【解决方案2】:

你可以试试:

library(dplyr)

df %>%
  mutate(newcolumn = case_when(is.na(col1) ~ NA_integer_, 
                               col1 == 'eat' | col2 == 'yes' ~ 1L, 
                               TRUE ~ 0L))

【讨论】:

  • 感谢 Ronak Shah,我在 col2 中有“yes”和“no”,在新列中,我希望“no”和“eat”也为 1。上面的代码改为 0。
  • @a24 请不要在 cmets 中扩展问题,编辑您的问题以包含您想要的条件。另请阅读有关how to ask a good question 以及如何提供reproducible example 的信息,以便更轻松地为您提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-07
  • 1970-01-01
  • 2017-07-19
  • 1970-01-01
相关资源
最近更新 更多