Is there a way to make the R mcmcplot() function not open a browser when it's called? I need to run my R code on a cluster and if mcmcplot() tries to open a browser, it will puke.
Can the output be dumped to a file maybe?
That function writes everything to a file and also opens it in a browser. If you dont want to open the browser I would recommend editing the function to pass whether or not you want to open in a browser as an argument. You can retreive the function by just typing its name without any parenthesis.
mcmcplot
then copy that output to a editor and at the beginning change the name of the function and add teh argument:
mcmcplotnew=function (mcmcout, parms = NULL, regex = NULL, random = NULL,
leaf.marker = "[\\[_]", dir = tempdir(), filename = "MCMCoutput",
extension = "html", title = NULL, heading = title, col = NULL,
lty = 1, xlim = NULL, ylim = NULL, style = c("gray", "plain"),
greek = FALSE,ShouldIPlotinbrowser=T) #new argument here
then there are much more parts of the function
then at the end there is
cat("\r", rep(" ", getOption("width")), "\r", sep = "")
cat("\n</div>\n</div>\n", file = htmlfile, append = TRUE)
.html.end(htmlfile)
full.name.path <- paste("file://", htmlfile, sep = "")
browseURL(full.name.path)
invisible(full.name.path)
}
Where you have the browsURL line, make it something like:
if(ShouldIPlotinbrowser) { browseURL(full.name.path) }
Then initialize that function before you run it with:
mcmcplotnew(whatever, usual, arguments,then,ShouldIPlotinbrowser=F)
Looking at the source, it seems not. There is an unconditional call to browseURL() there. Maybe by making a dummy version of that function which does nothing in your global namespace, it's effect can be avoided.
browseURL <- identity
This may break other browser activity as well, so after the mcmcplot calls, you may want to
rm(browseURL)
Alternatively, copy all the code from mcmcplot except for the browseURL line and use that function instead.
Related
I'm running the GCMS software AMDIS inside an R script to analyze GCMS data. The basic syntax is:
system("AMDIS_PATH GCMS_FILE_PATH /S /GC /GE /E"
With "/S /GC /GE /E" referring to functionalities within the AMDIS program.
I want to make the code 'fool-proof', so I'm allowing paths with "/" instead of "\\". And I'm also allowing spaces in the paths, escaping them with shQuote(..., type = "cmd")
Which means the full code looks like
system(paste(shQuote(gsub("/", "\\", AMDIS_PATH, fixed = T), type = 'cmd'), shQuote(gsub("/", "\\", GCMS_FILE_PATH, fixed = T), type = 'cmd'), "/S /GD /GS /E"))
This code does not work (output = 65535), but there's a catch:
If I remove the shQuotes from my GCMS_FILE_PATH. Then everything works like it should (so long as the FILE_PATH does not contain any spaces).
So executing the code like this does work:
system(paste(shQuote(gsub("/", "\\", AMDIS_PATH, fixed = T), type = 'cmd'), gsub("/", "\\", GCMS_FILE_PATH, fixed = T), "/S /GD /GS /E"))
Any idea why shQuote works fine for the AMDIS_PATH, but not for the GCMS_FILE_PATH? And how I can run my code and still escape spaces in the GCMS_FILE_PATH?
I use the following to create a D2L exam from the "capital.Rmd" example (I converted the question to schoice)
exams2blackboard("capitals.Rmd", n =3, name = "testquiz" )
After I upload the testquiz.zip file, I notice that the correct answer must be manually chosen on the D2L platform.
I was wondering if there is a workaround.
Many Thanks,
Umut
If you want the correct solution to be selected, do not use the Import option from the Question Library or from the Quiz itself. Use the Import/Export/Copy Components under the Course Admin tab.
If you import the questions through the following steps, BrightSpace correctly picks the right solution. It’s a bit longer but seems to correctly choose the solution.
Under the Course Admin tab of your course, go to
'Import/Export/Copy Components' -> ‘Import Components’ -> Start -> (drag and drop the ZIP file)
Click ‘Advanced Options…’
This step will take a few minutes for large files; if you do not click
Advanced Options, then the import will automatically import the
questions into the 'Question Library' and will generate a Quiz with the
imported questions; you do not want this.
-> Continue -> Continue -> at this point choose 'Question Library' from the section 'Select Components to Import'
I would not choose ‘Quizzes’ because it automatically creates a quiz
and makes it available to students. It has the unfortunate side-effect
of making ALL the questions available, which means all the versions of
various dynamic questions; this is not something we want.
-> Continue -> Continue. This stage takes a few minutes for large
imports.
Now the Questions are available in the Question Library and can be used to generate new quizzes. Each question has the correct answer selected already. This works for ‘schoice’ and ‘mchoice’ versions of questions. Currently, plots are not imported, though, still trying to figure out why.
This problem is new to me. In earlier versions of Brightspace/D2L the import of single-choice and multiple-choice exercises via exams2blackboard() worked well. Possibly, D2L changed in the meantime given that neither the current release version from CRAN nor the development version from R-Forge work for you.
D2L also supports other import formats and we did play around with some of these. See the following discussions in the R/exams forum on R-Forge:
https://R-Forge.R-project.org/forum/forum.php?thread_id=33404&forum_id=4377&group_id=1337
https://R-Forge.R-project.org/forum/forum.php?thread_id=33657&forum_id=4377&group_id=1337
Notably we tried to use the XML-based QTI 2.1 format that seems to be employed by D2L internally. However, D2L apparently uses a particular custom flavor of QTI 2.1. It should be possible to reverse engineer that and improve exams2qti21() correspondingly but so far (to the best of my knowledge) no one put the time and effort into this that would be needed.
For simple single/multiple choice questions a CSV-based exchange format can also be used. I have put together a very basic exams2d2l() function that was posted in the threads above and that I'm also including below. It can set up the CSV file for a single exercise like the capitals.Rmd exercise that you use above. For plain text exercises like that it seems to work well but not for more complex elements (graphics, code, math, etc.).
exams2d2l <- function(file, dir = ".", ## n = 1L, nsamp = NULL disabled for now
name = NULL, quiet = TRUE, edir = NULL, tdir = NULL, sdir = NULL, verbose = FALSE,
resolution = 100, width = 4, height = 4, svg = FALSE,
encoding = "", converter = NULL, ...)
{
## for Rnw exercises use "ttm" converter otherwise "pandoc" converter
if(any(tolower(tools::file_ext(unlist(file))) == "rmd")) {
if(is.null(converter)) converter <- "pandoc"
} else {
if(is.null(converter)) converter <- "ttm"
}
## output directory or display on the fly
## output name processing
if(is.null(name)) name <- tools::file_path_sans_ext(basename(file))
## set up .html transformer and writer function
htmltransform <- make_exercise_transform_html(converter = converter, ...)
## create exam with HTML text
rval <- xexams(file,
driver = list(sweave = list(quiet = quiet, pdf = FALSE, png = !svg, svg = svg,
resolution = resolution, width = width, height = height, encoding = encoding),
read = NULL, transform = htmltransform, write = NULL),
dir = dir, edir = edir, tdir = tdir, sdir = sdir, verbose = verbose)
## currently: only a single exercise
rval <- rval[[1L]][[1L]]
## put together CSV
cleanup <- function(x) gsub('"', '""', paste(x, collapse = "\n"), fixed = TRUE)
rval <- c(
'NewQuestion,MC,,,',
sprintf('ID,"%s",,,', cleanup(rval$metainfo$file)),
sprintf('Title,"%s",,,', cleanup(rval$metainfo$name)),
sprintf('QuestionText,"%s",,,', cleanup(rval$question)),
sprintf('Points,%s,,,', if(is.null(rval$metainfo$points)) 1 else rval$metainfo$points),
'Difficulty,1,,,',
'Image,,,,',
paste0('Option,', ifelse(rval$metainfo$solution, 100, 0), ',"', cleanup(rval$questionlist), '",,"', cleanup(rval$solutionlist), '"'),
'Hint,,,,',
sprintf('Feedback,"%s",,,', cleanup(rval$solution))
)
writeLines(rval, file.path(dir, paste0(name, ".csv")))
invisible(rval)
}
I'd like to have no images for the flipbox, how can I do it? Tried this (and also setting to NULL):
flipBox(
id = 1,
main_img = "",
header_img = "",
...
but instead it gives me this strange image.
I had the same problem and checked the source code of the function. If you copy it into a R script file there is the following code in line 13/14:
shiny::tags$img(class = "avatar",
src = main_img,
alt = "Avatar")
Since you cannot control this behavior by a flipBox() argument, I defined my own function flippBox and deleted the alt = "Avatar" argument. I do not see the necessity for this strange pill anyways..
Learning how to use R from the command line. I've come across the 'optparse' package and started using it. Thought everything was fine til I noticed it was not behaving as I initially expected, and couldn't make it write a file in the directory I wanted.
In order to keep things simple, I decided to use a short script to explain what's going on:
require(optparse)
#Parse arguments from command line
options <- list(
make_option(c("-d", "--directory"), action = "store", default = getwd(), type = "character", help="Working directory path."),
make_option(c("-e", "--extension"), action = "store", default = ".tsv", type = "character", help="File(s) extension."),
make_option(c("-p", "--outputPath"), action = "store", default = getwd(), type = "character", help="Output file(s) directory to be saved at."),
make_option(c("-o", "--outputName"), action = "store", default = "output", type = "character", help="Output file(s) base name."),
make_option(c("-s", "--separator"), action = "store", default = NA, help="Separator to use explicitely")
)
arguments <- parse_args(OptionParser(option_list = options))
setwd(arguments$d)
cat(arguments$d, arguments$e, arguments$s)
This works fine, it shows:
C:/Users/path/to/where/I/work .tsv NA
However, asking for the 'outputPath' and outputName' arguments
cat(arguments$p, arguments$o)
prints absolutely nothing... even though I explicitely gave those arguments a default value, a type, and an action. The outputPath option is literally the same thing as the directory option!
Using getwd(), as.character(getwd()), or even as.character(file.path(getwd())) gives the same result for the option 'outputPath'.
Passing the arguments from the command line (instead of using the default values) returns the exact same thing (what you'd expect for arguments$d, arguments$e, arguments$s, and nothing for arguments$p, arguments$o)
I am super confused about that; and of course, when trying to work with those variables in my real script... well it's impossible, cause it says that they have length zero...
Interestingly, if I do:
cat(unlist(arguments))
I do get the output I would expect... but I also get an additional logical variable with value FALSE, at the end of my argument list. I don't know where that came from...
C:/Users/path/to/where/I/work .tsv C:/Users/path/to/where/I/work output NA FALSE
I run this on the Windows powershell as:
Rscript.exe .\script.R
When I type the long flag (ex. --outputName something), the flag 'lights' and turns white on the terminal, whereas using the short one (ex. -o something) does not (it looks greyish on the command line, as if it is unused or something). Don't know if it means anything, since both do the exact same thing. Just wanted to point it out.
One last thing! Of course 'C:/Users/path/to/where/I/work' is not the real directory path, and the one I'm actually using has a whitespace on it... do you think that matters?
EDIT: Ok now I know where that FALSE came from, just needed to print my 'arguments' list... I feel dumb. But still, the original problem persists... and it confuses me more now, cause the values ARE stored in my 'argumens' list.
Doing:
arguments
Shows:
$directory
[1] "C:/Users/alang/Desktop/LabiVicenteLau D="
$extension
[1] ".tsv"
$outputPath
[1] "C:/Users/alang/Desktop/LabiVicenteLau D="
$output
[1] "output"
$separator
[1] NA
$help
[1] FALSE
Partial matching of arguments is your (I guess not) friend.
#!/usr/bin/env Rscript
require(optparse)
#Parse arguments from command line
options <- list(
make_option(c("-d", "--directory"), action = "store", default = getwd(), type = "character", help="Working directory path."),
make_option(c("-e", "--extension"), action = "store", default = ".tsv", type = "character", help="File(s) extension."),
make_option(c("-p", "--outputPath"), action = "store", default = getwd(), type = "character", help="Output file(s) directory to be saved at."),
make_option(c("-o", "--outputName"), action = "store", default = "output", type = "character", help="Output file(s) base name."),
make_option(c("-s", "--separator"), action = "store", default = NA, help="Separator to use explicitely")
)
arguments <- parse_args(OptionParser(option_list = options))
setwd(arguments$d)
print("R tries to match anything starting with an o.")
print(arguments$o)
print("No success")
print("R tries not to partially matchi anything. Explicitly call argument.")
print(arguments$outputPath)
print("Great success!")
The above script gives me:
romunov#kista ~/Documents
$ ./test.R
Loading required package: optparse
Warning message:
package 'optparse' was built under R version 3.5.3
[1] "R tries to match anything starting with an o."
NULL
[1] "No success"
[1] "R tries not to partially matchi anything. Explicitly call argument."
[1] "C:/Users/romunov/Documents"
[1] "Great success!"
do you see a way to run a computation in R while waiting for a user input?
I'm writing a script that makes differents types of plots which are defined by user input, but in first lot of data has to be loaded and processed. But in fact, user could start defining what he wants already while the processing is running - that's what I would like to do!
I think package Rdsn might provide the functionality that I need, but I was not able to figure out how.
Thanks!
You didn't give me much context, nor reproducible code, so I will just provide a simple example. I am not familiar with the Rdsn package, so I will use provide a solution I know.
# create a function to prompt the user for some input
readstuff = function(){
stuff = readline(prompt = "Enter some stuff: ")
# Here is where you set the condition for the parameter
# Let's say you want it to be an integer
stuff = as.integer(stuff)
if(is.na(stuff)){
return(readstuff())
} else {
return(stuff)
}
}
parameter = readstuff()
print(parameter)
print(parameter + 10)
The key here is to "source" the script instead of "running" it. You can find the "source" button on the top right of RStudio. You can also use source(yourscript) to source it.
So for every parameter you want to prompt the user for input, just call readstuff(). You can also tweak it a little to make it more general. For example:
# create a function to prompt the user for some input
readstuff = function(promptMessage = "stuff", class = "integer"){
stuff = readline(prompt = paste("Enter the", promptMessage, ": "))
# Here is where you set the condition for the parameter
# Let's say you want it to be an integer
stuff = as(stuff, class)
if(is.na(stuff)){
return(readstuff(promptMessage, class))
} else {
return(stuff)
}
}
plotColor = readstuff("plot color", "character")
size = readstuff("size parameter")
xvarName = readstuff("x axis name", "character")
df = data.frame(x = 1:100, y = 1:100)
library(ggplot2)
p = ggplot(df, aes(x = x, y = y, size = size, color = plotColor)) +
labs(x = xvarName) + geom_point()
print(p)
The if(is.na(stuff)) statements won't work if class is character, but I won't get into details on how to fix that, since this question is mainly about how to wait for user input. There are also ways to suppress the warning messages if the user entered something other than what is intended, but again, a bit off topic to talk about it here.
One important thing you have to watch out for is that anything you want R to print or plot, you need to wrap it with a print() function. Otherwise sourcing it won't print nor plot anything. Also, when typing in a parameter that is intended to be a string or character, don't add quotes. For example, for plotColor, type red instead of "red" in the prompt.
Most of the readline code are referenced from here: