【问题标题】:Is there a way to list values in na_if function in dplyr? [duplicate]有没有办法在 dplyr 的 na_if 函数中列出值? [复制]
【发布时间】:2021-12-18 11:35:55
【问题描述】:

我想使用 dplyr 包中的 na_if 函数列出我想要转换为丢失的 tibble 中的所有事件,但我似乎没有正确。有什么线索吗?

library(dplyr)

set.seed(123)

df <- tibble(
  a1 = c("one", "three", "97", "twenty", "98"),
  a2 = c("R", "Python", "99", "Java", "97"),
  a3 = c("statistics", "Data", "Programming", "99", "Science"),
  a4 = floor(rnorm(5, 80, 2))
)

#--- The long route

df1 <- df %>%
  mutate(across(where(is.character), ~na_if(., "97")),
         across(where(is.character), ~na_if(., "98")),
         across(where(is.character), ~na_if(., "99")))

#---- Trial

df2 <- df %>%
  mutate(across(where(is.character),
                ~na_if(., c("97", "98", "99"))))

【问题讨论】:

  • 根据the docu,不可能以这种方式使用na_if(即测试多个值)...可以找到可能的解决方案herehere,我敢肯定还有很多其他...但可能没有使用na_if
  • 来自上面的欺骗,适合您的用例:df2 &lt;- df %&gt;% mutate(across(where(is.character), ~ifelse( . %in% c("97", "98", "99"), NA, .)))

标签: r dplyr


【解决方案1】:

你可以使用:

df %>%
  mutate(
      across(
          where(is.character),
          ~if_else(. %in% c("97", "98", "99"), NA_character_, .)
      )
  )
# A tibble: 5 × 4
  a1     a2     a3             a4
  <chr>  <chr>  <chr>       <dbl>
1 one    R      statistics     80
2 three  Python Data           80
3 NA     NA     Programming    76
4 twenty Java   NA             83
5 NA     NA     Science        78

na_if 在这里不起作用的原因是因为~na_if(., c("97", "98", "99")) 基本上等同于if_else(. == c("97", "98", "99"), NA_character_, .)。换句话说,它只以成对的方式比较向量。您可以看到为什么这是一个问题:

> if_else(df$a1 == c("97", "98", "99"), NA_character_, df$a1)
[1] "one"    "three"  "97"     "twenty" NA      
Warning message:
In df$a1 == c("97", "98", "99") :
  longer object length is not a multiple of shorter object length

【讨论】:

    猜你喜欢
    • 2014-04-16
    • 2020-03-31
    • 1970-01-01
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 2021-07-03
    相关资源
    最近更新 更多