Rpython Copy String With Quotes From R To Python
I have trouble copying a string from R to a string in Python using RPython. I know the basic steps of doing it if the string does not have quotes but it gives error if the string h
Solution 1:
I'm also searching for good answer for this question. I can suggest workaround only:
Your example:
library('rPython')
python.exec("string=chr(39).join(['byte'])")
python.get("string")
[1] "byte"
# Alternatively: python.exec("string=chr(39) + \"byte\" + chr(39)")
# toget: [1] "'byte'"
Something more complex: Suppose 'I want' "something" like 'this'
library('rPython')
python.exec("string=\"Suppose \" + chr(39) + \"I want\" + chr(39) + \"\" + chr(34) + \"something\" + chr(34) + \" like \" + chr(39) + \"this\" + chr(39)")
python.get("string")
[1] "Suppose 'I want' \"something\" like 'this'"
Another example:
library('rPython')
python.exec("myCommand=\"gdal_translate -of GTiff -ot Int16 -a_nodata \" + chr(39) +\"-32768\" + chr(39) + \" NETCDF:\" + chr(39) + \"inputFile\" + chr(39) + \":Soil_Moisture \" + chr(39) + \"outputFile\" + chr(39)")
python.get("myCommand")
[1] "gdal_translate -of GTiff -ot Int16 -a_nodata '-32768' NETCDF:'inputFile':Soil_Moisture 'outputFile'"
Solution 2:
Borrowing from @matandked, you could replace single quotes with chr(39)
using gsub
:
library(rPython)
test <- "'byte'"
python.assign("string", gsub("\\'", "' + chr(39) + '", test))
python.get("string")
# [1] "'byte'"
There may be unintended consequences, but python.assign
could be modified in a similar fashion:
python.assign <- function (var.name, value, ...)
{
value <- gsub("\\'", "' + chr(39) + '", value) ## Added this line...
value <- toJSON(value, collapse = "", ...)
python.command <- c(paste(var.name, "='", value, "'", sep = " "),
paste(var.name, "= json.loads(", var.name, ")", sep = ""),
paste("if len(", var.name, ") == 1:", sep = ""), paste(" ",
var.name, "=", var.name, "[0]"))
python.command <- paste(python.command, collapse = "\n")
python.exec(python.command)
invisible(NULL)
}
## Now there's no need to substitute single quotes:
python.assign("string", test)
python.get("string")
# [1] "'byte'"
Post a Comment for "Rpython Copy String With Quotes From R To Python"