[英]Replace NA with Blank using Sql in R
我正在尝试使用 R 中的 Sql 将 NA 替换为空白。 我使用了下面的代码,但我仍然得到“NA”而不是空白!
DF_TEST_PN <- sqldf("Select *, Case when Proj_Loess ='NA' then ' ' else Proj_Loess end as New_Proj_Loess From Test")
您可以在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
假设我们有如下所示的 DF。 R 中的 NA 由 SQL 中的 null 表示,因此请使用coalesce
,如下所示。 coalesce
依次查看每个参数并返回不是 null 的第一个参数,即不是 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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.