[R] Creating/Reading a complex string in R

John McKown john.archie.mckown at gmail.com
Tue Jul 18 19:49:21 CEST 2017


On Tue, Jul 18, 2017 at 12:05 PM, Christofer Bogaso <
bogaso.christofer at gmail.com> wrote:

> Thanks for your pointer.
>
> Is there any way in R how to replace " ' " with " /' " programmatically?
>
> My actual string is quite lengthy, so changing it manually may not be
> possible. I am aware of gsub() function, however not sure I can apply
> it directly on my original string.
>
> Regards,
>
>
​I guess your string value is in a file? And you'd like to update the file
contents. You didn't say which OS you're on. I'm a Linux person, and the
simplest for me would be:

sed -i -r "s/'/\\'/g" myfile.txt​ #note the \\ becomes a single \ in the
output. weird.

Or just edit the file in your favorite editor. In mine, vim, it would be
the command ":g/'/s/\\'/g" (the command is within the " marks).
You are correct that you could use gsub(). But you can't just paste your
string into an R program as is, as you have already seen. You'd need to put
it into a file. Then read that file into a program (perhaps an R program
using gsub()) to write the updated string to another file. Which contents
you could then cut'n'paste into your original R file.
something like:

#!/usr/bin/Rscript
#
files <- commandArgs(trailingOnly=TRUE);
#
for (infile in files) {
        x=readLines(infile);
        y=gsub("'","\\\\'",x);
        ofile=paste0(infile,".new");
        writeLines(y,ofile);
}



-- 
Veni, Vidi, VISA: I came, I saw, I did a little shopping.

Maranatha! <><
John McKown

	[[alternative HTML version deleted]]



More information about the R-help mailing list