1
votes

In R using stringr package to perform string replace. The text file has 2 headers, a row 1 header and a sub-header, row 2. I use read_lines(n_max=1) to get one row and skip=n to position unto the next row. I need a correct regex or pattern to keep numeric data (and date data) in place while replacing "|" only with comma ",".

dat_subheader <- read_lines("1999-0.txt", skip=1, n_max=1)
dat_row1 <- read_lines("1999-0.txt", skip=2, n_max=1)
[1] "# XD|A Code|S Code|C Code|Site ID|Parameter|POC|Sample Duration|Unit|Method|Date|Start Time|Sample Value|Null Data Code|Sampling Frequency|Monitor Protocol (MP) ID|Qualifier - 1|Qualifier - 2|Qualifier - 3|Qualifier - 4|Qualifier - 5|Qualifier - 6|Qualifier - 7|Qualifier - 8|Qualifier - 9|Qualifier - 10|Alternate Method|Uncertain"
[1] "# XC|A Code|S Code|C Code|Site ID|Parameter|POC|Unit|Method|Year|Period|Number of Samples|Composite Type|Sample Value|Monitor Protocol (MP) ID|Qualifier - 1|Qualifier - 2|Qualifier - 3|Qualifier - 4|Qualifier - 5|Qualifier - 6|Qualifier - 7|Qualifier - 8|Qualifier - 9|Qualifier - 10|Alternate Method |Uncertain"

List of data contents:

[1] "XD|I|01|027|0001|88101|1|7|105|120|19990103|00:00||AS|3|||||||||||||"

Now using function, str_replace_all, to attempt to replace all occurrences of "|" to a comma ",". My str_replce_all() is thus set:

str_replace_all(dat_row1, "|", ",") 

But the result is replacing even the numeric data and dates with comma ",". I know I'm missing the correct pattern for this replace, need some helpful ideas. The vertical bar "|" only serves as a delimiter, and only this delimiter needs to be changed to comma ",". Would very much appreciate help in the right direction.

result showing incorrect replacements.

[1] ",X,D,|,I,|,0,1,|,0,2,7,|,0,0,0,1,|,8,8,1,0,1,|,1,|,7,|,1,0,5,|,1,2,0,|,1,9,9,9,0,1,0,3,|,0,0,:,0,0,|,|,A,S,|,3,|,|,|,|,|,|,|,|,|,|,|,|,|,"
1

1 Answers

0
votes

You need to use escape character \\

>str_replace_all("XD|I|01|027|0001|88101|1|7|105|120|19990103|00:00||AS|3|||||||||||||", "\\|", ",")
[1] "XD,I,01,027,0001,88101,1,7,105,120,19990103,00:00,,AS,3,,,,,,,,,,,,,"