How to replace "\0" with zero?

I have a csv file with one column of "\0", how can I replace this to zeros?

In data views, it shows :\0, but in R console, it shows: \0

I tried str_replace_all(data, "\0", "0") and got error message like:

Error: nul character not allowed (line 1)

Thanks!

Nuls are definitely annoying.

Can you give us a reproducible example (reprex) illustrating your issue? Please have a look at this guide, to see how to create one:

Maybe like this? In the file, there is only a single \ before the 0.

DF <- read.csv("c:/users/fjcc/Documents/R/Play/Dummy.csv", stringsAsFactors = FALSE)
DF
#>   Name value
#> 1    A   \\0
#> 2    b     3
#> 3    C     4
#> 4    D   \\0
#> 5    E     6
DF$value <- stringr::str_replace(DF$value, "\\\\0", "0")
DF
#>   Name value
#> 1    A     0
#> 2    b     3
#> 3    C     4
#> 4    D     0
#> 5    E     6

Created on 2020-02-03 by the reprex package (v0.3.0)

Actually I have multiple columns containing "\0" and there are all characters. sample data looks like:
df:
id var1 var2 var3 var4
1 A \0 \0 2
2 B \0 \0 3
3 C \0 \0 \0 5
4 D \0 \0 7
5 E \0 \0 \0 9

I want to use "0" as an integer to replace the columns var1 and var3 which are all "\0" and leave column var2 as it is. I used :
df2 <- apply(df,2,function(x){x=ifelse(x=="\0",0,x)}) %>%
as.data.frame()

But this code changed all "\0" and I noticed that every variable changes from character to factor.
Is there a way to solve this problem? Appreciated your help!

dput() function is a good way to share sample data with us, so we can help you.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.