I am using the RGoogleDocs package to upload a string of text to a document.
The following code is a minimal working example.
library(RGoogleDocs)
gpasswd = "mypassword"
auth = getGoogleAuth("example#gmail.com", gpasswd)
con = getGoogleDocsConnection(auth)
uploadDoc("test1", con, name = "d")
The problem: if I run this code twice two files named "d" appear.
In other words, the file is not replaced, even though in the function guide ?uploadDoc expected behaviour reads as
uploadDoc(content, con, name, type = as.character(findType(content)),
binary = FALSE, asText = FALSE, folder = NULL, ...)
-
name the name of the new document to be created (or the document to be replaced).
(Farrel Buchinsky brought this to my attention. It is often best to contact a package's author/maintainer if there is a problem as we don't necessarily follow both R-help and SO.)
Noah is right in saying just deleteDoc() and the uploadDoc().
We can do this in the uploadDoc() also.
I've just added a replace parameter to uploadDoc() (default is TRUE)
and that will (when I solve a possibly related bug)
a) move the current document, if it exists, to a temporary name
b) upload the new document to the target name,
c) delete the temporary document if the upload was successful
or, if not, move the temporary document back to the original name.
Something is up internally when testing this, but this should be in the next release.
I think the function guide here is a bit misleading. The uploadDoc function just creates a new document, and Google doesn't prevent you from having multiple docs named the same thing.
There is a stub in RGoogleDocs for updateDoc(), but it's been on the horizon for a while (last update of the package was 10/2009). I played for a few minutes, but would take some real digging to get it working.
Not a satisfying answer, but you could always just issue a deleteDoc() before re-uploading by the same name.
Related
I have this weird problem. I was able to get here() to work but it stopped working and I can't figure out how to fix it.
So basically the structure of my file is like:
C:/First/Second/Third/Analysis/Scripts
C:/First/Second/Third/Analysis/Data
I want to easily bounce between data and scripts in the code
If I type here("C:/First/")
and then follow up with here(), R says that I'm at
C:/First/Documents
I'm not able to type here("Second", "Third", "Analysis", "Data", "todayscode.R")
because it puts me in the folder:
C:/First/Documents/Second/Third/Analysis/Data/
Which obviously does not exist.
It's unclear why you say that C:/First/Documents/Second/Third/Analysis/Data/ "does not exist". You will need to create a subdirectory if it doesn't exist, but at the beginning of your problem presentation you implied that was an existing directory.
Sounds like you want something like this possibilities:
setwd("C:/First/Second/Third/Analysis/")
You should first clarify where your version of the here function is coming from by typing here at the console input line and noting which namespace it comes from. If you then wanted to refer to a directory with that starting point you could use this (using the example set up in the here package at the here help page):
library(here); library(readr)
readr::read_csv(
here("data", "penguins.csv"),
col_types = list(.default = readr::col_guess()),
n_max = 3
)
I am using exams2pdf() to generate two PDF files as:
exams2pdf(file = "ICvar.Rmd",
name = "icvar",
engine = "knitr",
verbose = FALSE,
texdir = "tmptex",
template = c("exam", "solution")
)
But I get this error:
Error in base::file(out_tex[j], open = "w+", encoding = encoding) : invalid 'description' argument
Any ideas why?
Also, is it possible to use custom templates in exams2nops() like template = c("exam", "solution") to produce two PDF files, the first with the questions; the second with the solutions? I read the vignette but could not find any information and adding template to options in exams2nops() does nothing.
The problem is that you only provide a single name = "icvar" but actually need two distinct names for template = "exam" and template = "solution", respectively. Hence, lacking a second name lead to the somewhat cryptic error message. A simple solution is to provide a vector of two name = c("icex", "icsol"), say.
Additionally, I have just committed a fix to the development version on R-Forge that points this out more clearly in ?exams2pdf, throws an intelligible warning, and provides a workaround. If you use your code above, name is changed to name = c("icvar_exam", "icvar_solution") automatically.
As for exams2nops(): Internally this essentially sets up a standardized template via make_nops_template() and then calls exams2pdf(). No additional templates can be provided. The reason for this is that all the convenient options in the NOPS template (e.g., adding an intro, selecting the language, switching to twocolumn layout, etc.) would only work for the NOPS template but not the other templates provided. Therefore, if you want to produce a solution sheet you have to use another call to exams2pdf() (or exams2html() or exams2pandoc()) after setting the same random seeds as for exams2nops().
I am creating a package and would like to store settings data locally, since it is unique for each user of the package and so that the setting does not have to be set each time the package is loaded.
How can I do this in the best way?
You could save your necessary data in an object and save it using saveRDS()
whenever a change it made or when user is leaving or giving command for saving.
It saves the R object as it is under a file name in the specified path.
saveRDS(<obj>, "path/to/filename.rds")
And you can load it next time when package is starting using loadRDS().
The good thing of loadRDS() is that you can assign a new name to the obj. (So you don't have to remember its old obj name. However the old obj name is also loaded with the object and will eventually pollute your namespace.
newly.assigned.name <- loadRDS("path/to/filename.rds")
# or also possible:
loadRDS("path/to/filename.rds") # and use its old name
Where to store
Windows
Maybe here:
You can use %systemdrive%%homepath% environment variable to accomplish
this.
The two command variables when concatenated gives you the desired
user's home directory path as below:
Running echo %systemdrive% on command prompt gives:
C:
Running echo %homepath% on command prompt gives:
\Users\
When used together it becomes:
C:\Users\
Linux/OsX
Either in the package location of the user,
path.to.package <- find.package("name.of.your.pacakge",
lib.loc = NULL, quiet = FALSE,
verbose = getOption("verbose"))
# and then construct with
destination.folder.path <- file.path(path.to.package,
"subfoldername", "filename")`
# the path to the final destination
# You should use `file.path()` to construct such paths, because it detects automatically the correct ('/' or '\') separators for the file paths in Unix-derived systems (Linux/Mac Os X) versus Windows.
Or use the $HOME variable of the user and there in a file - the name of which beginning with "." - this is convention in Unix-systems (Linux/Mac OS X) for such kind of file which save configurations of software programs.
e.g. ".your-packages-name.rds".
If anybody has a better solution, please help!
I'm currently building a shiny application that needs to be translated in different languages. I have the whole structure but I'm struggling into getting values such as "Validació" that contain accents.
The structure I've followed is the following:
I have a dictionary that is simply a csv with the translation where
there's a key and then each language. The structure of this dictionary is the following:
key, cat, en
"selecció", "selecció", "Selection"
"Diferències","Diferències", "Differences"
"Descarregar","Descarregar", "Download"
"Diagnòstics","Diagnòstics", "Diagnoses"
I have a script that once the dictionary.csv is modified, generates a .bin file that later will be loaded in the code.
In strings.R I have all the strings that will appear on the code and I use a function to translate the current language to the one I want. The function is the following:
Code:
tr <- function(text){
sapply(text, function(s) translation[[s]][["cat"]], USE.NAMES=F)
}
When I translate something, since I am doing in another file, I assign it to another variable something like:
str_seleccio <- tr('Selecció)
The problem I'm facing is that for example if we translate 'Selecció' would be according to this function, tr('Selecció') and provides a correct answer if I execute it in the RStudio terminal but when I do it in the Shiny application, appears to me as a NULL. If the word I translate has no accents such as "Hello", tr("Hello") provides me a correct answer in the Shiny application and I can see it throught the code.
So mainly tr(word) gets the correct value but when assigning it "loses the value" so I'm a bit lost how to do it.
I know that you can do something like Encoding(str_seleccio) <- "UTF-8" but in this case is not working. In case of plain words it used to do but since when I asssign it, gets NULL is not working.
Any idea? Any suggestion? What I would like is to add something to tr function
The main idea comes from this repository that if you can take a look is the simplest version you can do, but (s)he has problem with utf-8 also.
https://github.com/chrislad/multilingualShinyApp
As in http://shiny.rstudio.com/articles/unicode.html suggested (re)save all files with UTF-8 encoding.
Additionaly change within updateTranslation.R:
translationContent <- read.delim("dictionary.csv", header = TRUE, sep = "\t", as.is = TRUE)
to:
translationContent <- read.delim("dictionary.csv", header = TRUE, sep = "\t", as.is = TRUE, fileEncoding = "UTF-8").
Warning, when you (re)save ui.R, your "c-cedilla" might get destroyed. Just re-insert it, in case it happens.
Happy easter :)
good day people,
I'm working on a word based reports automation task. These reports are basically some standard text, a dozen or so charts, some numeric/trend text values that I need to populated based on logic. The trend text, numeric values or charts are to be generated from backend database.
I'm able to produce a blank document with charts using database, the R packages I used are ReporteRs, RODBC, officer and corresponding dependency packages, ggplot2 for charts.
However what I would like to achieve is, have a word document template with some sort of placeholders where I can put the charts and these numeric values.
I've basic code as following
doc <- docx(title="my doc")
mychart <- ggplot(.....)
doc <- addPlot(doc, fun=print, x = mychart)
writeDoc(doc, filename)
Can anyone advise how to approach this task. I saw usage of template parameter in docx but I couldn't find suitable examples of putting values in placeholders or putting charts at particular placeholders inside Word document.
Hope I've explained it clearly, if not please let me know.
Ok I've figured out how to achieve it finally.
MS-Word allows putting placeholders in document and bookmark them so that values/data/images can be put in their place.
You can create a normal word document(not as word template) and add your static content in it along with bookmarked placeholders as per your requirements.
Please refer here to know how to add bookmarks , Word doesn't show existing bookmarks by default, to enable that go to File -> Options -> Advanced check Show bookmarks, you'll see [your_bookmark] thing in square brackets.
Next in R, try following code
doc <- docx(title="title", template="c://above_template.docx")
doc = addPlot(doc, x=myChartVariable, bookmark="your_chart_bookmark)
writeDoc(doc, "c://new_doc_file_path.docx:)
you should see new file with a chart substituted where you put its placeholder.
I would recommend using VBA for this, not R. Do some google-research on DocVariables in Word. Add some DocVariables to your Word template, keep your analytics in Excel, and then push what you have in Excel into the Word DocVariables. Use the script below, which runs in Excel, to make everything work.
Sub PushToWord()
Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
sWdFileName = Application.GetOpenFilename(, , , , False)
Set doc = objWord.Documents.Open(sWdFileName)
'On Error Resume Next
objWord.ActiveDocument.variables("BrokerFirstName").Value = Range("BrokerFirstName").Value
objWord.ActiveDocument.variables("BrokerLastName").Value = Range("BrokerLastName").Value
objWord.ActiveDocument.variables("Ryan").Value = Range("Ryan").Value
objWord.ActiveDocument.Fields.Update
'On Error Resume Next
objWord.Visible = True
End Sub
Finally, add a reference to Word, from Excel. Tools > References > Microsoft Word xxx Object Library.