【问题标题】:Replace all string instances of "NULL" with actual NULL or NA in a data frame [duplicate]将“NULL”的所有字符串实例替换为数据框中的实际 NULL 或 NA [重复]
【发布时间】:2021-08-05 11:17:12
【问题描述】:

我想知道是否有一种方法可以用 NULL 或 NA 替换 DF 中跨多个字段的字符串“NULL”的所有实例?

exampledf <- data.frame(
  a = c("NULL", "1/1/20", "2/28/20"),
  b = c("NULL", "blah", "ha"),
  c = c("NULL", "NULL", "cat")
)

是否有一个行将整个 df 中的“NULL”替换为 NULL 或 NA?

【问题讨论】:

  • 另见123
  • @camille 是的,谢谢!
  • 如果该帖子解决了它,您应该能够将自己的问题标记为该问题的重复

标签: r


【解决方案1】:

使用dplyr

library(dplyr)
exampledf <- exampledf %>%
      mutate(across(everything(), na_if, "NULL"))

【讨论】:

    【解决方案2】:

    这样做:

    exampledf[exampledf=="NULL"] <- NA
    

    dplyr

    exampledf <- exampledf %>% replace(exampledf == "NULL", NA)
    

    【讨论】:

    • 谢谢!暂时开放,以防有人有 tidyverse 方法可以在管道内使用 exampledf %&gt;%
    【解决方案3】:

    我们可以像下面这样使用replace

    > replace(exampledf, exampledf == "NULL", NA)
            a    b    c
    1    <NA> <NA> <NA>
    2  1/1/20 blah <NA>
    3 2/28/20   ha  cat
    

    【讨论】:

      猜你喜欢
      • 2021-01-02
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 2022-10-23
      • 2012-11-14
      • 1970-01-01
      • 1970-01-01
      • 2017-06-13
      相关资源
      最近更新 更多