How to add answer specific feedback to dist3.Rmd? - r

I'm looking at the dist3.Rmd example template from here: http://www.R-exams.org/templates/dist3/. The solution markdown is the general feedback provided after submission. I want to create feedback.
Solution
========
The distance $d$ of $p$ and $q$ is given by
$d^2 = (p_1 - q_1)^2 + (p_2 - q_2)^2$ (Pythagorean formula).
Hence $d = \sqrt{(p_1 - q_1)^2 + (p_2 - q_2)^2} =
\sqrt{(`r p[1]` - `r q[1]`)^2 + (`r p[2]` - `r q[2]`)^2}
= `r round(sol, digits = 3)`$.
\
```{r distplot, echo = FALSE, results = "hide", fig.path = "", fig.cap = ""}
par(mar = c(4, 4, 1, 1))
plot(0, type = "n", xlim = c(0, 6), ylim = c(0, 6), xlab = "x", ylab = "y")
grid(col = "slategray")
points(rbind(p, q), pch = 19)
text(rbind(p, q), c("p", "q"), pos = c(2, 4))
lines(rbind(p, q))
lines(c(p[1], p[1], q[1]), c(p[2], q[2], q[2]), lty = 2)
```
If the answer choice is correct, I'd like the general feedback to popup and if the answer is wrong, I'd like for the pythagorean formula and the image prompt to show up but not the calculation. How can I accomplish this?

Given your jargon about "general feedback" I assume this is related to Moodle and the exams2moodle() interface in R/exams.
I tried to find out whether the feature you describe can be specified using Moodle XML format but was not successful. So at the moment this is certainly not possible in R/exams and I'm not sure whether it would be possible in Moodle XML. If anyone is aware of a solution in Moodle XML, I would be interested and could check whether it would be possible to add this to exams2moodle().
Update: Following the discussion in the comments with #ArvindMurali I briefly discuss here how it is possible to include images in the specific feedback from the "solution list". However, I still don't see how to separate specific and general feedback between different iterations of answering the question.
If you make a copy of dist3.Rmd to, say, dist4.Rmd you just need to modify two lines. In the options for the r distplot code chunk in line 35, add fig.show = "hide". And in the r solutionlist chunk in line 46 replace the answerlist(...) command with:
answerlist(ifelse(sc$solutions,
"This is correct!",
"This is not correct, please consider: <br/> ![](distplot-1.png)"),
markup = "markdown")
For preparing this for Moodle you then need to use pluginfile = FALSE so that the image is really embedded directly into the specific feedback (rather than via Moodle's plugin file declaration).
set.seed(1)
exams2moodle("dist4.Rmd", pluginfile = FALSE)
Then, the specific feedback for each incorrect item will display the plot from the r distplot chunk.
The formatting is not great but it works - so far so good.
The problem is that in addition to this specific feedback, the general feedback will also be displayed at the end - always, as far as I can see. If there were a way to delay this in Moodle, then I could check whether it is possible to interface this in R/exams.

Related

Error while knitting R-markdown to pdf: must be a finite number

Knitting my File produces the error message down below:
This is how my File starts:
Unfortunately, I couldn't try anything as I have no idea what the error message has to do with the displayed information.
I hope to knit the document to a pdf once this error has been removed.
My code:
library(plotrix)
p6<-pie3D(rawdata8.2$rawdata8.1,
col = hcl.colors(length(data), "Spectral"),
radius = 1.7,
theta = 0.25,
shade = 0.5,
height = 0.3,
start = pi/1.25,
explode = 0.2)
title("Anzahl Ankünfte nach Herkunftsland der Touristen 2020" )
The most obvious problem is that you are probably asking for a palette of length 1:
hcl.colors(1, "Spectral")
Error in seq.int(1, by = -2/(n - 1), length.out = n2) :
'by' must be a finite number
This happens because hcl.colors tries to set up a step size -2/(n-1), which is infinite if n==1.
Guessing beyond this what's going on: unless you have explicitly defined an object called data in your workspace, R will find the built-in function data(): length(data) is 1 (as it seems all functions have length 1 - not quite sure what the logic is here ...)
Also keep in mind that if you have a data frame df, length(df) will give you the number of columns — you would need nrow(df) to get the number of rows ...
The problem is probably in your 3Dpie and not in the fact that you are knitting to pdf.
Please consider checking pie3D documentation. And try to run the code of that particular chunk in your console.
Check this example for instance: did you provide both values and labels for your pie-chart?
Does it help to set the radius back to 1? Not sure if it can be higher in user units?
Have you defined pi somewhere? Or do you need to call it from a math package?
These are some ideas. I hope it helps.
This problem might also help.

Suppress graph output of a function [duplicate]

I am trying to turn off the display of plot in R.
I read Disable GUI, graphics devices in R but the only solution given is to write the plot to a file.
What if I don't want to pollute the workspace and what if I don't have write permission ?
I tried options(device=NULL) but it didn't work.
The context is the package NbClust : I want what NbClust() returns but I do not want to display the plot it does.
Thanks in advance !
edit : Here is a reproducible example using data from the rattle package :)
data(wine, package="rattle")
df <- scale (wine[-1])
library(NbClust)
# This produces a graph output which I don't want
nc <- NbClust(df, min.nc=2, max.nc=15, method="kmeans")
# This is the plot I want ;)
barplot(table(nc$Best.n[1,]),
xlab="Numer of Clusters", ylab="Number of Criteria",
main="Number of Clusters Chosen by 26 Criteria")
You can wrap the call in
pdf(file = NULL)
and
dev.off()
This sends all the output to a null file which effectively hides it.
Luckily it seems that NbClust is one giant messy function with some other functions in it and lots of icky looking code. The plotting is done in one of two places.
Create a copy of NbClust:
> MyNbClust = NbClust
and then edit this function. Change the header to:
MyNbClust <-
function (data, diss = "NULL", distance = "euclidean", min.nc = 2,
max.nc = 15, method = "ward", index = "all", alphaBeale = 0.1, plotetc=FALSE)
{
and then wrap the plotting code in if blocks. Around line 1588:
if(plotetc){
par(mfrow = c(1, 2))
[etc]
cat(paste(...
}
and similarly around line 1610. Save. Now use:
nc = MyNbClust(...etc....)
and you see no plots unless you add plotetc=TRUE.
Then ask the devs to include your patch.

R tools gageRR response input not clear

I am interested in using the gageRR function in one of my projects offered by r tools.
In the following code:
gdo = gageRRDesign(3,10, 2, randomize = FALSE)
y = c(23,22,22,22,22,25,23,22,23,22,20,22,22,22,24,25,27,28,23,24,23,24,24,22,
22,22,24,23,22,24,20,20,25,24,22,24,21,20,21,22,21,22,21,21,24,27,25,27,
23,22,25,23,23,22,22,23,25,21,24,23)
response(gdo) = y
gdo = gageRR(gdo, tolerance = 5)
summary(gdo)
plot(gdo)
How should i organize my data to input to y? There seems to be no explanation for this online.
Ps sorry for not giving proper code format for the code as this option is not available on stackoverflow on my phone.

Why can't the pdf file created by gage (a R packge) be opened

I am trying to use Gage package implemented in R to analyze my RNA-seq data. I followed the tutorial and got my data.kegg.p file and I used the following script to generate the heatmap for the top gene set
for (gs in rownames(data.kegg.p$greater)[1]) {
outname = gsub(" |:|/", "_", substr(gs, 10, 100))
geneData(genes = kegg.gs[[gs]], exprs = essData, ref = 1,
samp = 2, outname = outname, txt = T, heatmap = T,
Colv = F, Rowv = F, dendrogram = "none", limit = 3, scatterplot = T)
}
I did get a pdf file named "NOD-like_receptor_signaling_pathway.geneData.heatmap.pdf", but when I open this file with acrobat reader or photoshop, it gives the error information that this file has been disrupted and cannot be recovered. Could anyone help check this file (https://www.dropbox.com/s/wrsml6n1pbrztnm/NOD-like_receptor_signaling_pathway.geneData.heatmap.pdf?dl=0) to see whether it is really disrupted and is it possible to find a way to recover it?
I also attached the R workspace file (https://www.dropbox.com/s/6n5m9x5hyk38ff1/A549.RData?dl=0). The object "a4" is the data with the format ready for gage analysis. It contains the data of the reference sample (nc) the treated sample (a549). It can be accepted by gage for analysis but generate the heatmap pdf file which cannot be opened (above). Would you mind helping me check whether these data can be properly used to generated the correct gage result?
Best regards.
I'm running into a similar problem myself. Not 100% sure but I think this problem occurs when there is no heatmap to plot. In my case, I was doing as.group comparison with ref and sample selections. I think the software treats this circumstance as a sample n of 1 and can't really show a differential heatmap. When I tried using 1ongroup setting, I was able to visualize the pdf file.

How to find byte sizes of R figures on pages?

I would like to monitor the basic quality of the figures produced in R on individual pages such as byte size of each page,...
I can now do only quality assurance of average pages, see the following chapter about it.
I think there must be something builtin for the task than average measures.
Code which produces 4 pages in Rplots.pdf where I would like to know the byte size of each page in an output here; any other statistics of the page outputs is also welcome;
you can get the basic memory monitoring by objects here but I would like it to correspond to the outputs in PDF
# https://stat.ethz.ch/R-manual/R-devel/library/graphics/html/plot.html
require(stats) # for lowess, rpois, rnorm
plot(cars)
lines(lowess(cars))
plot(sin, -pi, 2*pi) # see ?plot.function
## Discrete Distribution Plot:
plot(table(rpois(100, 5)), type = "h", col = "red", lwd = 10,
main = "rpois(100, lambda = 5)")
## Simple quantiles/ECDF, see ecdf() {library(stats)} for a better one:
plot(x <- sort(rnorm(47)), type = "s", main = "plot(x, type = \"s\")")
points(x, cex = .5, col = "dark red")
## TODO summarise here the byte size of figures in the figures (1-4)
# Output: Rplot.pdf where 4 pages; I want to know the size of each page in bytes
I am currently doing the basic quality assurance in command-line but would like to move some of it to R, to observe bugs faster.
Expected output: byte size, for instance like 4th column of ls -l
To get bytesize of average individual page in an output document
Limitations
Requirement of the homogeneity of the data in pages. This method only works if the pages are all from the same sample.
Otherwise, it is troublesome because it is only average, not describing then the individual phenomenons.
Other possible weaknesses
PDF-elements and meta data. Consider PDF-file as whole, not focusing on the graphic objects itself. So this limits the absolute value use because the filesize contains also headers and other meta data which are not about the graphic objects.
Code
filename <- "main.pdf"
filesize <- file.size(filename)
# http://unix.stackexchange.com/q/331175/16920
pages <- Rpoppler::PDF_info(filename)$Pages
# print page size (= filesize / pages)
pagesize <- filesize / pages
## data of example file
num 7350960
int 62
num 118564
Input: just any 62-pages document
Output: average individual page size (118564)
Testing and's answer
Output but you cannot change the input easily to your wanted PDF-file
files size_bytes
[1,] "./test_page_size_pdf/page01.pdf" "4,123,942"
[2,] "./test_page_size_pdf/page02.pdf" " 4,971"
[3,] "./test_page_size_pdf/page03.pdf" " 4,672"
[4,] "./test_page_size_pdf/page04.pdf" " 5,370"
Input: just any 64-pages document
Expected output: 67 (= 64 + 3) pages, not 4 analysed
R: 3.3.2
OS: Debian 8.5
Download and install the pdftk utility if it is not already on your system and then try one of the following alternatives this from within R.
1) It will return a data frame with the page file sizes in bytes and other information.
myfile <- "Rplots.pdf"
system(paste("pdftk", myfile, "burst"))
file.info(Sys.glob("pg_*.pdf"))
It will also generate a file doc_data.txt with some miscellaneous information that may or may not be of interest.
1a) This alternative will not generate any files. It will simply return the character sizes of the pages as a numeric vector.
myfile <- "Rplots.pdf"
pages <- as.numeric(read.dcf(pipe(paste("pdftk", myfile, "dump_data")))[, "NumberOfPages"])
cmds <- sprintf("pdftk %s cat %d output - | wc -c", myfile, seq_len(pages))
unname(sapply(cmds, function(cmd) scan(pipe(cmd), quiet = TRUE)))
The above should work if pdftk and wc are on your path. Note that on Windows you can find wc in the Rtools distribution and is typically at "C:\\Rtools\\bin\\wc" once Rtools is installed.
2) This alternative is similar to (1) but uses the animation package:
library(animation)
ani.options(pdftk = "/path/to/pdftk")
pdftk("Rplots.pdf", "burst", "pg_%04d.pdf", "")
file.info(Sys.glob("pg_*.pdf"))
To measure the size of each page in a pdf-file I suggest this:
test_size <- TRUE
pdf_name <- "masterpiece"
if(test_size){
dir.create("test_page_size_pdf")
pdf_address <- paste0("./test_page_size_pdf/page%02d.pdf")
} else { pdf_address <- paste0("./", pdf_name, ".pdf")}
pdf(pdf_address, width=10, height=6, onefile=!test_size)
par(mar=c(1,1,1,1), oma=c(1,1,1,1))
plot(rnorm(10^6, 100, 5), type="l")
plot(sin, -pi, 2*pi)
plot(table(rpois(100, 5)), type = "h", col = "red", lwd = 10,
main = "rpois(100, lambda = 5)")
plot(x <- sort(rnorm(47)), type = "s", main = "plot(x, type = \"s\")")
points(x, cex = .5, col = "dark red")
dev.off()
if(test_size){
files <- paste0("./test_page_size_pdf/", list.files("./test_page_size_pdf/"))
size_bytes <- format(file.size(files), big.mark = ",")
file.remove(files)
file.remove("test_page_size_pdf")
cbind(files, size_bytes)
}
The size of a pdf-page in R depends on three things: the content of the plot(), the options used in the pdf() function and the plotting options which are here defined in par().
All this is difficult to estimate. You mention also that you like to have something similar to the shell function ls, which run on files as well. So in this solution I create a temporary folder dir.create() in which we save every page of the pdf separately in a file. We implement this with the option onefile. When the plotting is finish every pdf-page-file as well as the temporary folder will be deleted. And you can see the result in the console.
If you are finish with the testing and want the result in a single file you just have to change in the first line of this script the variable test_size <- FALSE. By the way; I have some doubt that the size of a page is a proxy for the quality of an image. Pdf is a vector format, so the size correspondent with the number of elements: see the size of the first page in my example where I plot 1mio points.

Resources