How to replace empty values with NULL in R?

时间:2023-01-07 11:46:25

I wrote functions in R how to replace invalid characters in my df content. The code is below.

我在R中写了函数如何替换我的df内容中的无效字符。代码如下。

     # Replace invalid characters in the df content
df <- apply(df, 2, function(x) gsub(",", ".", x))
df <- apply(df, 2, function(x) gsub("'", "", x))
df <- apply(df, 2, function(x) gsub("?", "", x))
df <- apply(df, 2, function(x) gsub("!", "", x))
df <- apply(df, 2, function(x) gsub("'", "", x))
df <- apply(df, 2, function(x) gsub("@", "", x))
df <- apply(df, 2, function(x) gsub("$", "", x))
df <- apply(df, 2, function(x) gsub("\"", "", x))
df <- apply(df, 2, function(x) gsub("^$", NULL, x))

In some dataframes I have empty values which become 0. I want to make them NULL. The last line of code I wrote to replace empty value with NULL but not getting the result. Could you tell me what I'm doing wrong?

在一些数据帧中,我有空值,它变为0.我想使它们为NULL。我编写的最后一行代码用NULL替换空值但没有得到结果。你能告诉我我做错了什么吗?

Unfortunately, I can't use NA. In the database it should arrive as NULL. I'm using SQL loader script written in R. It doesn't need to be gsub necessarily.

不幸的是,我不能使用NA。在数据库中,它应该以NULL形式到达。我正在使用R编写的SQL loader脚本。它不一定是gsub。

1 个解决方案

#1


2  

Maybe you can use NA instead NULL, like this:

也许你可以使用NA代替NULL,如下所示:

df <- apply(df, 2, function(x) gsub("", NA, x))

#1


2  

Maybe you can use NA instead NULL, like this:

也许你可以使用NA代替NULL,如下所示:

df <- apply(df, 2, function(x) gsub("", NA, x))