R storing quotation marks without backslash - r

I need to do a loop for a POST request.
The post looks something like this:
r <- POST(http://decentralization.gov.ua/graphql?query={community(id:"2"){title}})
And I need to replace the "2" for a an i (loop). The problem is that R scapes the quotation marks with a backslash, and the post function take those backslash as part of the address.
I have tried combining single and double quotes, sprintf() and dQuote()
The result is always the same:
"http://decentralization.gov.ua/graphql?query={community(id:\"i\"){title}}"
and I believe those backslashes are messing up the post request (status_code: 400).
Is there any way to store a string with quotation marks without the backslashes?

You could probably paste the URL within every iteration. The following code worked for me:
for (i in 1:2) {
url <- paste0('http://decentralization.gov.ua/graphql?query={community(id:"', i, '"){title}}')
res <- httr::POST(url = url)
}

Related

How to encode strings in R with double backslashes?

Is there any easy way in R to encode strings with double backslashes?. I extracted some data from a website and realised that words in the data were decoded. The following is part of the data:
'"option_name\":\"\\uc81c\\ud488\\uc120\\ud0dd#$%\\uc0c9\\uc0c1\"'
I want it to be:
'"option_name":"제품선택#$%색상"'
If I manually replace double backslashes from the string and print, it works fine but I want to avoid manual work with this. It would be great if someone could help me with this issue?
Given the example provided, it does not appear to have "double backslashes" -- perhaps you mean double quotes?
In either case, the string on the right of the colon is in Unicode, so something like this will encode correctly:
string <- "\uc81c\ud488\uc120\ud0dd#$%\uc0c9\uc0c1"
new_string <- enc2utf8(string)
cat(new_string)
"제품선택#$%색상"
If you want to treat the entire selection as one string, you can wrap it in single quotes:
string <- '"option_name":"\uc81c\ud488\uc120\ud0dd#$%\uc0c9\uc0c1"'
new_string <- enc2utf8(string)
cat(new_string)
"option_name":"제품선택#$%색상"
# to remove the double quotes at the same time:
new_string <- gsub('\"', "", enc2utf8(string))
cat(new_string)
option_name:제품선택#$%색상

In R, Is there a way to break long string literals? [duplicate]

I want to split a line in an R script over multiple lines (because it is too long). How do I do that?
Specifically, I have a line such as
setwd('~/a/very/long/path/here/that/goes/beyond/80/characters/and/then/some/more')
Is it possible to split the long path over multiple lines? I tried
setwd('~/a/very/long/path/here/that/goes/beyond/80/characters/and/
then/some/more')
with return key at the end of the first line; but that does not work.
Thanks.
Bah, comments are too small. Anyway, #Dirk is very right.
R doesn't need to be told the code starts at the next line. It is smarter than Python ;-) and will just continue to read the next line whenever it considers the statement as "not finished". Actually, in your case it also went to the next line, but R takes the return as a character when it is placed between "".
Mind you, you'll have to make sure your code isn't finished. Compare
a <- 1 + 2
+ 3
with
a <- 1 + 2 +
3
So, when spreading code over multiple lines, you have to make sure that R knows something is coming, either by :
leaving a bracket open, or
ending the line with an operator
When we're talking strings, this still works but you need to be a bit careful. You can open the quotation marks and R will read on until you close it. But every character, including the newline, will be seen as part of the string :
x <- "This is a very
long string over two lines."
x
## [1] "This is a very\nlong string over two lines."
cat(x)
## This is a very
## long string over two lines.
That's the reason why in this case, your code didn't work: a path can't contain a newline character (\n). So that's also why you better use the solution with paste() or paste0() Dirk proposed.
You are not breaking code over multiple lines, but rather a single identifier. There is a difference.
For your issue, try
R> setwd(paste("~/a/very/long/path/here",
"/and/then/some/more",
"/and/then/some/more",
"/and/then/some/more", sep=""))
which also illustrates that it is perfectly fine to break code across multiple lines.
Dirk's method above will absolutely work, but if you're looking for a way to bring in a long string where whitespace/structure is important to preserve (example: a SQL query using RODBC) there is a two step solution.
1) Bring the text string in across multiple lines
long_string <- "this
is
a
long
string
with
whitespace"
2) R will introduce a bunch of \n characters. Strip those out with strwrap(), which destroys whitespace, per the documentation:
strwrap(long_string, width=10000, simplify=TRUE)
By telling strwrap to wrap your text to a very, very long row, you get a single character vector with no whitespace/newline characters.
For that particular case there is file.path :
File <- file.path("~",
"a",
"very",
"long",
"path",
"here",
"that",
"goes",
"beyond",
"80",
"characters",
"and",
"then",
"some",
"more")
setwd(File)
The glue::glue function can help. You can write a string on multiple lines in a script but remove the line breaks from the string object by ending each line with \\:
glue("some\\
thing")
something
I know this post is old, but I had a Situation like this and just want to share my solution. All the answers above work fine. But if you have a Code such as those in data.table chaining Syntax it becomes abit challenging. e.g. I had a Problem like this.
mass <- files[, Veg:=tstrsplit(files$file, "/")[1:4][[1]]][, Rain:=tstrsplit(files$file, "/")[1:4][[2]]][, Roughness:=tstrsplit(files$file, "/")[1:4][[3]]][, Geom:=tstrsplit(files$file, "/")[1:4][[4]]][time_[s]<=12000]
I tried most of the suggestions above and they didn´t work. but I figured out that they can be split after the comma within []. Splitting at ][ doesn´t work.
mass <- files[, Veg:=tstrsplit(files$file, "/")[1:4][[1]]][,
Rain:=tstrsplit(files$file, "/")[1:4][[2]]][,
Roughness:=tstrsplit(files$file, "/")[1:4][[3]]][,
Geom:=tstrsplit(files$file, "/")[1:4][[4]]][`time_[s]`<=12000]
There is no coinvent way to do this because there is no operator in R to do string concatenation.
However, you can define a R Infix operator to do string concatenation:
`%+%` = function(x,y) return(paste0(x,y))
Then you can use it to concat strings, even break the code to multiple lines:
s = "a" %+%
"b" %+%
"c"
This will give you "abc".
This will keep the \n character, but you can also just wrap the quote in parentheses. Especially useful in RMarkdown.
t <- ("
this is a long
string
")
I do this all of the time. Use the paste0() function.
Rootdir = "/myhome/thisproject/part1/"
Subdir = "subdirectory1/subsubdir2/"
fullpath = paste0( Rootdir, Subdir )
fullpath
> fullpath
[1] "/myhome/thisproject/part1/subdirectory1/subsubdir2/"

How can I replace "map-09" by `map-09` in R? (from double quotes to single quotes)

I tried with gsub, and str_replace, but I didn't get what I need.
gsub("\"", "\`", "map-09", fixed=TRUE)
gives "map-09" and not map-09
str_replace("map-09","\"","\`")
gives "map-09" and not map-09
I think you're getting confused between the way the string is being represented vs. what the string actually is. The functions you're using don't actually add any quotes. But when the output is printed quotes are there to show you that it is a string being represented. If you use the function 'cat' to print the output you'll see it without the quotes.
See the difference between
print("example")
cat("example")

substitute single backslash in R

I have read some questions and answers on this topic in stack overflow but still don't know how to solve this problem:
My purpose is to transform the file directory strings in windows explorer to the form which is recognizable in R, e.g. C:\Users\Public needs to be transformed to C:/Users/Public, basically the single back slash should be substituted with the forward slash. However the R couldn't store the original string "C:\Users\Public" because the \U and \P are deemed to be escape character.
dirTransformer <- function(str){
str.trns <- gsub("\\", "/", str)
return(str.trns)
}
str <- "C:\Users\Public"
dirTransformer(str)
> Error: '\U' used without hex digits in character string starting ""C:\U"
What I am actually writing is a GUI, where the end effect is, the user types or pastes the directory into a entry field, pushes a button and then the program will process it automatically.
Would someone please suggest to me how to solve this problem?
When you need to use a backslash in the string in R, you need to put double backslash. Also, when you use gsub("\\", "/", str), the first argument is parsed as a regex, and it is not valid as it only contains a single literal backslash that must escape something. In fact, you need to make gsub treat it as a plain text with fixed=TRUE.
However, you might want to use normalizePath, see this SO thread.
dirTransformer <- function(str){
str.trns <- gsub("\\\\", "/", str)
return(str.trns)
}
str <- readline()
C:\Users\Public
dirTransformer(str)
I'm not sure how you intend the user to input the path into the GUI, but when using readline() and then typing C:\Users\Public unquoted, R reads that in as:
> str
[1] "C:\\Users\\Public"
We then want to replace "\\" with "/", but to escape the "\\" we need "\\\\" in the gsub.
I can't be sure how the input from the user is going to be read into R in your GUI, but R will most likely escape the \s in the string like it does when using the readline example. the string you're trying to create "C:\Users\Public" wouldn't normally happen.

Changing "/" into "\" in R

I need to change "/" into "\" in my R code. I have something like this:
tmp <- paste(getwd(),"tmp.xls",sep="/")
so my tmp is c:/Study/tmp.xls
and I want it to be: c:\Study\tmp.xls
Is it possible to change it in R?
Update as per comments.
If this is simply to save the file, then as #sgibb suggested, you are better off using file.path():
file.path(getwd(), "tmp.xls")
Update 2: You want double back-slashes.
tmp is a string and if you want to have an actual backslash you need to escape it -- with a backslash.
However, when R interprets the double slashes (for example, when looking for a file with the path indicated by the string), it will treat the seemingly double slashes as one.
Take a look at what happens when you output the string with cat()
cat("c:\\Study\\tmp.xls")
c:\Study\tmp.xls
The second slash has "disappeared"
Original Answer:
in R, \ is an escape character, thus if you want to print it literally, you need to escape the escape character: \\. This is what you want to put in your paste statement.
You can also use .Platform$file.sep as your sep argument, which will make your code much more portable.
tmp <- paste(getwd(),"tmp.xls",sep=.Platform$file.sep)
If you already have a string you would like to replace, you can use
gsub("/", "\\", tmp, fixed=TRUE)

Resources