I have question with interactive Rmd, which I am not even sure if it is possible.
So I have made a function that takes 4 inputs in command to run. I am wondering if I can make a program/ line that lets the user input the inputs in the Rmd (html).
for example,
if a line to ran a 'run_function' function is
run_function(1,2,"3",4)
I wonder if I can configure smt on Rmd to prompt the user to input each variables
Enter var 1: x
Enter var 2: y
Enter var 3: "5"
Enter var 4: f
to ran the following command automatically
-> run_function(x,t,"5",f)
Will this be possible? In R, without using python?
I am attaching my function and exp output
run_diff<-function(model_in, contr_in,graph_title,txt_title){
t<-diff(df_filt,model_in,contr_in)
write.table(t, file = txt_title, row.names = F, sep = "\t", quote = F)
print(head(t,10))
DEsites_count<-as.integer(length(which(t$adj.P.Val < 0.05)))
string<-"Number of Differentially Editing sites are"
print(paste(string, DEsites_count))
g<- ggplot(t, aes(x=logFC, y=-log10(P.Value))) +
theme_minimal() +geom_jitter(aes(color=AveExpr), alpha=0.3, size = 2)+
theme(text = element_text(size = 10))+
ggtitle(graph_title)
print(g)
}
run_diff(model_2,"contr_1", "Model_2, contr1","model_2_contr_1_toptable.txt")
-> produces a table, a graph, and saves a txt file
Not possible if the command executes in R. Rmd renders static html files. The options you have are to use JavaScript in the Rmd to do what I think you intend or create a Rshiny markdown app. The later is dependent on the client having R on their machine or the app being hosted on a shinyserver. Itβs important to note the Rmd when knitted executes the R code and translates or captures the outputs in html, JS and CSS.
Related
(Newb to R)
Writing a Qmd file for a report for a small project (partly to learn R for future projects)
Running each chunk whilst is editor works fine
source("MyGraphFile", local = knitr::knit_global())
mycommand_fromgraphfile
#generating a simple histogram
The code from the Graphs R file "MyGraphFile":
mycommand_fromgraphfile <-
ggplot(mydata, aes(agey))+
geom_histogram(color = 'white',
fill = scico::scico(1, begin = .3, palette = "berlin"),
bins = 20) +
labs(x = "Age",
y = "Count") +
scale_y_continuous(
breaks = scales::pretty_breaks()
)
When I go to render this as html, pdf etc. I get this error when it runs the first chunk above with source("MyGraphFile....
Quitting from lines 29-32 (report.qmd)
Error in ggplot(mydata, aes(ageyears)) :
object 'mydata' not found
Calls: .main ... eval -> source -> withVisible -> eval -> eval -> ggplot
As I say, when running each chunk sequentially from the source/visual editor all works fine
I only get the above error when rendering the file
I've also tried simply running the whole ggplot command from within the qmd file, and not sourcing back to the graph R file, same error.
It seems the qmd file can't see the datafile when rendering? I've tested it with some of the example datasets and it renders fine, so clearly something I've missed. I've tried saving the datafile from previous cleaning and loading at the beginning of the qmd file, no luck
Any help for a n00b?
My question has been answered
The Quarto render needs the dataset loading
I'm trying to knit a PDF document and set the following global settings because I want all the code and comments to appear inside the document (otherwise long lines of code or comments extend beyond the border of the page):
knitr::opts_chunk$set(message=FALSE, tidy.opts=list(width.cutoff=40), tidy=TRUE)
The problem is that tidy=TRUE also causes some of my code to display on the same line despite being on a new line in my script. So this chunk:
ggplot(data = keffects_20, aes(x = k, y = avg_tests, group = pool_size)) +
geom_boxplot() +
xlab("Pool Size (k)") +
ylab("Mean Number of Tests per Person") +
scale_y_continuous(breaks = seq(0, 1.25, 0.25)) +
theme_classic()
actually appear as this.
But I'd like it to look like this (the same way it is written in the chunk).
The only way I'm able to get that desired format is by setting tidy=FALSE but then that causes my long lines of code to run off of the page. Is there any way to get both my long lines of code to stay on the page while also having new lines appear on a new line?
I think the tidy = FALSE option is the only way to do what you want. But you can limit that to just one statement by putting that statement in a chunk by itself.
Even better: write your source in the format you want from the beginning, or format it in the source document, and leave tidy = FALSE in all chunks.
I'm trying to execute the below code that display a plot:
using Plots, Measures
pyplot()
data = [rand(100), rand(100)];
histogram(data, layout = 2,
title = ["Dataset A" "Dataset B"], legend = false,
ylabel = "ylabel", margin = 5mm)
I do not get any output once I execute it from the command line!!
Knowing that I tried it in 3 different ways and it works (Jupyter, Juni, Julia session), though I'm confused about the way it works in the Juno, kinldy see my observations below:
With Jupyter it is functioning perfectly:
With Juno, I've to run the file TWICE!! the first time looks to be for compilation, second time for execution, maybe!!
And if I closed the plot, I've to close the Julia session, restart it, then re-execute the file TWICE!! and sometimes nothing is appearing!!
With Julia session, it take time for first time execution, then if I closed the plot and run it again, it is appearing smoothly.
The commands like histogram or plot typically don't display the plots for users, they only generate and return the plots.
What displays the plots is actually the display system in Julia.
When Julia is in interactive use, like in REPL, Jupyter and Juno, the display system will be invoked automatically with commands not ending with ";". That's why you see plots displayed in REPL, Jupyter and Juno.
But when executing the file from the command line, the display system is not automatically activated. So you first have to invoke display yourself like this:
using Plots, Measures
pyplot()
data = [rand(100), rand(100)];
h = histogram(data, layout = 2,
title = ["Dataset A" "Dataset B"], legend = false,
ylabel = "ylabel", margin = 5mm)
display(h)
But even this will not give you the picture, but only text representation of the plot. This is because in command line julia, only a very simple text display system is in place, and it doesn't have "full" support for plots from Plots. To display the plots, you have to write your own display mechanism and push it to Julia display system, which is not hard but a little tedious. I will give an example when I have more time.
BTW, if you just want plots generated from command line, another way is to save it to files, which is more direct than making a display mechanism yourself.
Update
Here is a simple display, which mimics the display system used in Julia REPL. The code here is for Julia 0.7/1.0.
const output = IOBuffer()
using REPL
const out_terminal = REPL.Terminals.TerminalBuffer(output)
const basic_repl = REPL.BasicREPL(out_terminal)
const basic_display = REPL.REPLDisplay(basic_repl)
Base.pushdisplay(basic_display)
Using it before the previous code will show the plot. Please note that you use pyplot() backend for Plots, whose default is to open a new window and display the plot in the window, but when the julia finish execution in the command line, it will close the plot window. To deal with this, we could either change ways for the default display, or use another backend to show the plot, for example, plotly() backend will display the plot through html. The complete code may look like following:
const output = IOBuffer()
using REPL
const out_terminal = REPL.Terminals.TerminalBuffer(output)
const basic_repl = REPL.BasicREPL(out_terminal)
const basic_display = REPL.REPLDisplay(basic_repl)
Base.pushdisplay(basic_display)
using Plots, Measures
plotly()
data = [rand(100), rand(100)];
h = histogram(data, layout = 2,
title = ["Dataset A" "Dataset B"], legend = false,
ylabel = "ylabel", margin = 5mm)
display(h)
Use readline() to get such destination that close the plot window by typing enter.
using GR
y = rand(20,1)
p = plot(y,linewidth=2,title="My Plot")
readline()
I have issue with plotting lines over my existing plot in .Rmd in RStudio. I ran the code within the code chunk in .Rmd (β + return) and the plot gives me a graph within the .Rmd (new feature of RStudio v1.0), however when I ran the second code lines, an error shows up.
plot(density(with$glucose),
ylim = c(0.00, 0.02),
xlab = "Glucose Level",
main = "Figure",
lwd = 2)
lines(density(without$glucose),
col = "red",
lwd = 2)
Error in plot.xy(xy.coords(x, y), type = type, ...) : plot.new has not been called yet
On the other hand, if I copy and paste the codes into the console, I could get the plot I want, in the plot viewer within RStudio.
In addition, when I ran some other codes within the .Rmd (β + return), my plots in the plot viewer in RStudio disappear. This means I have to do copy-paste into the console instead of using the (β + return) shortcut.
Does anyone have the same problem?
This is a known problem, but you can solve it very easy: Press Ctrl+Shift+Enter to run the complete chunk, then everything works fine and you don't have to copy-and-paste all thing to the console.
So do all your plots in one chunk and run this chunk. This will produce you the plot within the RMD file (as you mentioned: new feature of RStudio 1.0)
If you're not a fan of the inline output / notebook mode for R Markdown documents, you can also disable it within the Global Options dialog -- try disabling the option:
Show output inline for all R Markdown document
I'm working with sjPlot in order to get "pretty" tables. I managed to create a really nice contingency and another table providing me with frequencies of a variable.
Everything is just nice and the way it should be - except for one thing:
I work with RStudio and when I run my code that includes several sjPlot-tables as output, I can only access the latest one. Unlike the graphics-window of RStudio, where you can click back and forth through your output, I'm stuck here with just the last table.
Is there a way to create a new tab or window or so, that I can run my code and get access to all the tables I created?
That would be super cool!
Currently, there is no history feature for the Viewer pane in RStudio. You may open the tables in your browser instead (or additional, there's an icon in the Viewer pane), so you have multiple browser tabs, each with a table output.
Or you "concat" multiple tables and show them in the Viewer pane, however, this is quite an effort to do.
# create and save first HTML-table
part1 <- sjt.lm(fit1, fit2)
# create and save second HTML-table
part2 <- sjt.lm(fit3, fit4)
# browse temporary file
htmlFile <- tempfile(fileext=".html")
write(sprintf("<html><head>%s</head><body>%s<p></p>%s</body></html>",
part1$page.style,
part1$page.content,
part2$page.content),
file = htmlFile)
viewer <- getOption("viewer")
if (!is.null(viewer)) viewer(htmlFile) else
utils::browseURL(htmlFile)
Thanks Daniel!
That actually really helps a lot!
I also figured out (which is why I'm posting this as an answer and not just as a comment...) that windows() also creates new data windows through RStudio.
This might be interesting to other RStudio users as well :-)
Here's some example code just quickly copied out of my script:
scatter <- ggplot(na.action=na.exclude, spending.analysis, aes(age, money))
windows()
scatter +
geom_point(aes(color = school), alpha = 0.7) +
geom_smooth( method = "lm", color = "dark blue", alpha = 0.05, fill = "blue", na.action = na.exclude) +
facet_grid(. ~ school) +
theme_bw() +
scale_color_manual(values = group.colors)
I think this explains where to put the windows() command