【问题标题】:Replace NA with Blank using Sql in R使用 R 中的 Sql 将 NA 替换为空白
【发布时间】:2020-07-28 20:55:08
【问题描述】:

我正在尝试使用 R 中的 Sql 将 NA 替换为空白。我使用了下面的代码,但我仍然得到“NA”而不是空白!

DF_TEST_PN

【问题讨论】:

  • 我怀疑 NA 正是 R 显示缺失值的方式。

标签: sql r


【解决方案1】:

你可以在sqldf/sqLite中使用ifnull

test <- tibble(Proj_Loess=c(NA,"test"))
DF_TEST_PN <- sqldf("Select *, ifnull(Proj_Loess,' ') as New_Proj_Loess From test")

  Proj_Loess New_Proj_Loess
1       <NA>               
2       test           test

【讨论】:

    【解决方案2】:

    假设我们有如下所示的 DF。 R 中的 NA 在 SQL 中由 null 表示,因此请使用coalesce,如下所示。 coalesce 依次查看每个参数并返回第一个不为空的参数,即非 NA。 coalesce 在 sqldf 支持的所有后端(sqlite、h2、mysql、postgresql)中都可用。

    library(sqldf)
    
    DF <- data.frame(A = c("A", NA, "B", NA, "C"))
    sqldf("select *, coalesce(A, '') as V1 from DF")
    

    给予:

         A V1
    1    A  A
    2 <NA>   
    3    B  B
    4 <NA>   
    5    C  C
    

    如果您想在问题中使用case when,请像这样使用is null

    sqldf("select *, case when A is null then '' else A end as V1 from DF")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-17
      • 2013-11-04
      • 1970-01-01
      • 1970-01-01
      • 2015-10-09
      • 2021-07-02
      相关资源
      最近更新 更多