How to disable source() file echo in R? - r

According to the documentation, source() takes a default option echo = verbose, which can get old fast when testing functions. How can I set this to be FALSE just for source() in a simple way (such as an .Rprofile setting)?
I tried setting options(echo=FALSE) but that throws a wrench in the terminal functioning:
> options(echo=FALSE)
5
[1] 5
options(echo=TRUE)
>

If you are using RStudio, the Source button can perform either "Source" or "Source with Echo" using the little dropdown arrow to select between then. The button will then continue to run with the last chosen option.

How about
library(Defaults)
setDefaults("source",echo=FALSE)
?
This is similar to (but not quite identical/somewhat simpler than) the answer to this question.
Since the Defaults package was archived 6 months after this question was answered, you either would have to get it from here or use devtools::install_version("Defaults","1.1-1"), or fall back to #KonradRudolph's answer.

Redefine source:
source = function (file, local = FALSE, print.eval = echo,
verbose = getOption("verbose"),
prompt.echo = getOption("prompt"), max.deparse.length = 150,
chdir = FALSE, encoding = getOption("encoding"),
continue.echo = getOption("continue"), skip.echo = 0,
keep.source = getOption("keep.source")) {
base::source(file, local, echo = FALSE, print.eval, verbose, prompt.echo,
max.deparse.length, chdir, encoding, continue.echo, skip.echo,
keep.source)
}
Terrible, I know. But effective.

No, source does not take a "default option". It takes a logical argument echo, which defaults to the value of verbose. If the caller doesn't pass verbose either, that argument, in turn, defaults to getOption("verbose"). So if you wanted to set a global option to affect echoing of the input text, you would do options(verbose=FALSE). BTW, that's the setting of this option by default anyway, so you only need to change any of the above if you set it differently.

Related

R/exams d2l multiple choice question doesn't select correct answer

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)
}

R shinydashboardplus flipbox - how to remove images

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..

Confused about passing arguments from command line (optparse) R, arguments not getting stored even with explicit 'default' option

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!"

R code mcmcplots function

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.

how to increase the limit for max.print in R

I am using the Graph package in R for maxclique analysis of 5461 items.
The final output item which I get is very long, so I am getting the following warning:
reached getOption("max.print") -- omitted 475569 rows
Can somebody please provide me the pointers with how to increase the limit
for max.print.
Use the options command, e.g. options(max.print=1000000).
See ?options:
‘max.print’: integer, defaulting to ‘99999’. ‘print’ or ‘show’
methods can make use of this option, to limit the amount of
information that is printed, to something in the order of
(and typically slightly less than) ‘max.print’ _entries_.
See ?options:
options(max.print=999999)
You can use the options command to change the max.print value for the value limit you want to reach. For example:
options(max.print = 1000000)
There you can change the value of the max.print in R.
set the function options(max.print=10000) in top of your program. since you want intialize this before it works. It is working for me.
I fixed it just now. But it looks busty. Anyone make it simple please?
def list_by_tag_post(request):
# get POST
all_tag = request.POST.getlist('tag_list')
arr_query = list(all_tag)
for index in range(len(all_tag)):
tag_result = Tag.objects.get(id=all_tag[index])
all_english_text = tag_result.notes.all().values('english_text', 'id')
arr_query[index] = all_english_text
for index in range(len(arr_query)):
all_english_text = all_english_text | arr_query[index]
# Remove replicated items
all_english_text = all_english_text.order_by('id').distinct()
# render
context = {'all_english_text': all_english_text, 'all_tag': all_tag}
return render(request, 'list_by_tag.html', context)

Resources