简体   繁体   English

在 R 中使用 Sql 将 NA 替换为空白

[英]Replace NA with Blank using Sql in R

I am trying to replace NA with Blank using Sql in R.我正在尝试使用 R 中的 Sql 将 NA 替换为空白。 I used below code but I still get "NA" instead of blank!我使用了下面的代码,但我仍然得到“NA”而不是空白!

DF_TEST_PN <- sqldf("Select *, Case when Proj_Loess ='NA' then ' ' else Proj_Loess end as New_Proj_Loess From Test") DF_TEST_PN <- sqldf("Select *, Case when Proj_Loess ='NA' then ' ' else Proj_Loess end as New_Proj_Loess From Test")

You can use ifnull in sqldf / sqLite :您可以在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

Suppose we have DF as shown below.假设我们有如下所示的 DF。 The NAs in R are represented by null in SQL so use coalesce as shown below. R 中的 NA 由 SQL 中的 null 表示,因此请使用coalesce ,如下所示。 coalesce looks at each argument in turn and returns the first one that is not null, ie not NA. coalesce依次查看每个参数并返回不是 null 的第一个参数,即不是 NA。 coalesce is available in all backends that sqldf supports (sqlite, h2, mysql, postgresql). 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")

giving:给予:

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

If you want to use case when as in the question then use is null like this:如果您想在问题中使用case when则使用is null ,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM