QMD and R - Object not found when rendering - r

(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

Related

interactive function command in R

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.

No such file or directory Knit R markdown

I am attempting to knit a markdown that I have been working on for Google Data Analytics Professional Certificate Capstone. I have the markdown near completed and would like to see how it delivers, however, when I attempt to knit I receive "no such file or directory" error. This was not occurring for me while working on the markdown as I was simultaneously using the knit function to the view the work. It happened when I changed the output from html_notebook to word_document. I changed it back to html_notebook and am still receiving the same error. I have provided a caption of the error message. I understand it has something to do with the directory however I have the .RMD located in the same folder as the imported data sets which I create the data frame from. I am running that code using a data frame that is in my environment so why would markdown not be able to find this data? Any help would be appreciated! Also, when I take out new_sleep_averages code it then returns the same error on my next visualization with a different data frame.
the issue is because
new_sleep_averages
is not found. perhaps you renamed the variable name or the name does not exist.
Check Line 51, and trace where new_sleep_averages is created
I have found the answer via another stack overflow question. Here is the link
Can't resolve error in .Rmd file <Anonymous> ... withCallingHandlers -> withVisible -> eval -> eval ->
I installed this line of code at the top of my document and everything ran fine.
knitr::opts_chunk$set(error = TRUE)
-- This however did not load graphs there were still errors in the code which were solved by inputting the individual code chunks for each graph within the markdown. For example I only had
user6_hr_April12 %>%
mutate(user6_hr_April12, Time = as.POSIXct(Time, format = "%m/%d/%Y %I:%M:%OS %p")) %>%
ggplot(aes(x = Time, y = Value)) +
geom_line() +
theme_bw() +
scale_x_datetime(breaks = "1 hour", date_labels = "%I:%M %p") +
theme(axis.text.x = element_text(angle = 45)) +
ggtitle("heart rate user_6",
subtitle = "4-12-2016")
but had to input the code for read.csv and all the cleaning I did as well.

How to place new lines of code on a new line in a knitted PDF in R Markdown?

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.

RMarkdown - all cells run without error but when document is knitted errors occur

This one is strange. In an R markdown document, every single code cell displays its output without error, but when I try to knit the document into html, I get an error:
Error: stat_bin() must not be used with a y aesthetic. Execution halted
The closest code I could find to the line number and the last cell name to flash by before the error occurred was this:
g + geom_histogram() # default: bins=30 (for diamonds: 5.01 - 0.2 / 30)
g <- ggplot(data = diamonds, aes(x = carat))
g + geom_histogram(binwidth = 1) # not fine grained enough
g + geom_histogram(binwidth = 0.1)
g + geom_histogram(binwidth = 0.01) # too fine grained
A confusing aspect of the RStudio environment is that things can be loaded in memory that no longer reflect the current state of the code.
In the example given, g was changed in an earlier cell, but its clean perfect output continued to display in the later cell. Once all code errors were tracked down. The document then knitted correctly.
Among the things that needed to be addressed:
All packages in use need an explicit declaration as in
library(dplyr). Some were in memory but not included in any of the
markdown cells.
eval cannot be FALSE on any cell whose code effects later
markdown cells, but include can be FALSE if the goal is to leave
that cell out of the final knitted document.
Code loading data from files needed to get paths checked and included
because the working directory got changed from what it was when files
were loaded.
These are some of the things that can throw off the knit process, but once addressed, then the document should knit fine. Know any more things to check? Feel free to edit this post and add them in.
Thought about deleting this post after I caught my mistakes but decided to write this up in case helpful for anyone else. Best wishes.

Plotting device with RStudio

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

Resources