I'm completely new to using quarto. But one thing I wonder is if there is any chance to use a dataframe created "on the fly" in the quarto document in an observable (ojs) chunk, instead of maybe writing it out as CSV and reading it in? I guess there is no way at all, but you never know:)
So something like this:
df = data.frame(
x = 1:10,
y = 2:11
)
{
// somehow get access to the df
}
Use the ojs_define() function to make data processed in Python or R available to {ojs} cells (this function should be called in the R or Python cell).
See more here in the Quarto Documentation.
Related
I am using a summary() function from an R package. It prints out multiple results by using cat() and print() functions interweavingly (I checked its source code by getAnywhere()). It uses cat() to output descriptive messages, and uses print() to print out the dataframe and the matrix that I wanted to save. I am using R notebook, so I can see the cat() output and matrix output in the R Console tab, and the dataframe output by itself in another result tab. I wasn't able to save or retrieve the dataframe.
I tried sink() and capture.output() functions, but it only saved the descriptive messages and matrix together in a text file, and no dataframe saving. Does anyone know how to retrieve the dataframe object by itself? And I may also need to retrieve the matrix object by itself too.
The R package is called "lmmlasso". I guess it's not very well maintained. Here I am just giving an example code:
summary.foo= function(){
cat("random effects\n")
print(matrix(rnorm(9),3))
cat("fixed effects \n")
print(data.frame(X = c("A","B","C"), Estimate = rnorm(3)))
}
summary.foo()
I was not able to solve it directly, so I turned to the alternative way: I copied the original source code, return the dataframe and matrix objects at the end, and changed its function name. I got the dataframe by using the new summary function.
You should provide a reproducible code.
Anyway, try to assign it to a variable and then use the variable attributes, either with $ or #, to access the output you desire
Is there anyway I can store the results of one variable in one R script, and make them available to another R script?
I have this basic script in one file:
B5b=fit(y~.,d_treino_both,model="randomforest",task="class")
P5b=predict(B5b,d_teste)
x=d_teste$y
m5b=mmetric(x,P5b,metric=c("ACC","ACCLASS","CONF", "ROC"))
mgraph(x,P5b,graph= "ROC", baseline=TRUE)
print(m5b)
P5b
Then, I want to make the resuts of P5b variable available to another script.
Any help?
Not sure if this is what you are looking for. I think one way you can do that is to source the script1 in script2. I would do something like this and remove any additional variables using rm.
source("script1.R")
Perhaps you could try something with dput and the clipboard. Basically, this is just copying the dput of an object to the clipboard and then evaluating the clipboard in the second script. Note that you cannot use the clipboard in the meantime.
# first script
obj <- capture.output(dput(matrix(1:100, 10, 10)))
writeClipboard(str = obj)
# second script
obj2 <- eval(parse(text = readClipboard()))
I am interested in writing a function where it takes a data frame as an input and returns an html page via knitr as an output based on the information in the data frame.
Here is sort of the psuedocode of the function that I wanted to write:
htmlOuput <- function(Df) {
newDf<-someManipulation(Df)
meltedDf<-melt(Df)
g<-ggplot(meltedDf)
return (html(g)) # This is the part that I am not sure about
}
Is there a way to output an html page as a function output via knitr ?
After some research I found that calling an rmarkdown file to render within a function to be the best option.
htmlOuput <- function(Df,meta = NULL, cacheable = NA) {
rmarkdown::render('./report.rmd',params=list(output_file = report.html))
}
Where the report.rmd will contain the manipulation of the data frame
newDf<-someManipulation(Df)
meltedDf<-melt(Df)
g<-ggplot(meltedDf)
g
I guess you took the hard way.
An easy approach would be to use htmlTable
I have used that to export to html and it is easy to use.
I am using tableNominal{reporttools} to produce frequency tables. The way I understand it, tableNominal() produces latex code which has to be copied and pasted onto a text file and then saved as .tex. But is it possible to simple export the table produced as can be done in print(xtable(table), file="path/outfile.tex"))?
You may be able to use either latex or latexTranslate from the "Hmisc" package for this purpose. If you have the necessary program infrastructure the output gets sent to your TeX engine. (You may be able to improve the level of our answers by adding specific examples.)
Looks like that function does not return a character vector, so you need to use a strategy to capture the output from cat(). Using the example in the help page:
capture.output( TN <- tableNominal(vars = vars, weights = weights, group = group,
cap = "Table of nominal variables.", lab = "tab: nominal") ,
file="outfile.tex")
I do a lot of data exploration in R and I would like to keep every plot I generate (from the interactive R console). I am thinking of a directory where everything I plot is automatically saved as a time-stamped PDF. I also do not want this to interfere with the normal display of plots.
Is there something that I can add to my ~/.Rprofile that will do this?
The general idea is to write a script generating the plot in order to regenerate it. The ESS documentation (in a README) says it well under 'Philosophies for using ESS':
The source code is real. The objects are realizations of the
source code. Source for EVERY user modified object is placed in a
particular directory or directories, for later editing and
retrieval.
With any editor allows stepwise (or regionwise) execution of commands you can keep track of your work this way.
The best approach is to use a script file (or sweave or knitr file) so that you can just recreate all the graphs when you need them (into a pdf file or other).
But here is the start of an approach that does the basics of what you asked:
savegraphs <- local({i <- 1;
function(){
if(dev.cur()>1){
filename <- sprintf('graphs/SavedPlot%03d.pdf', i)
dev.copy2pdf( file=filename )
i <<- i + 1
}
}
})
setHook('before.plot.new', savegraphs )
setHook('before.grid.newpage', savegraphs )
Now just before you create a new graph the current one will be saved into the graphs folder of the current working folder (make sure that it exists). This means that if you add to a plot (lines, points, abline, etc.) then the annotations will be included. However you will need to run plot.new in order for the last plot to be saved (and if you close the current graphics device without running another plot.new then that last plot will not be saved).
This version will overwrite plots saved from a previous R session in the same working directory. It will also fail if you use something other than base or grid graphics (and maybe even with some complicated plots then). I would not be surprised if there are some extra plots on occasion that show up (when internally a plot is created to get some parameters, then immediatly replaced with the one of interest). There are probably other things that I have overlooked as well, but this might get you started.
you could write your own wrapper functions for your commonly used plot functions. This wrapper function would call both the on-screen display and a timestamped pdf version. You could source() this function in your ~/.Rprofile so that it's available every time you run R.
For latice's xyplot, using the windows device for the on-screen display:
library(lattice)
my.xyplot <- function(...){
dir.create(file.path("~","RPlots"))
my.chart <- xyplot(...)
trellis.device(device="windows",height = 8, width = 8)
print(my.chart)
trellis.device(device = "pdf",
file = file.path("~", "RPlots",
paste("xyplot",format(Sys.time(),"_%Y%m%d_%H-%M-%S"),
".pdf", sep = "")),
paper = "letter", width = 8, height = 8)
print(my.chart)
dev.off()
}
my.data <- data.frame(x=-100:100)
my.data$y <- my.data$x^2
my.xyplot(y~x,data=my.data)
As others have said, you should probably get in the habit of working from an R script, rather than working exclusively from the interactive terminal. If you save your scripts, everything is reproducible and modifiable in the future. Nonetheless, a "log of plots" is an interesting idea.