As I mentioned earlier, I’m the process of learning R and RStudio. As I hit stumbling blocks with RStudio, I’m posting solutions here. I’m posting partially as a reference for me so I can remember how to fix a problem, but also in hopes it helps others.
Problem: Running a command in the console works perfectly, but when creating an R Markdown file in R Studio, it fails.
Imagine that I have a data frame called “farmers” that contains data on the amount of produce a farmer sells at farmer’s market. The data frame came from a .csv file that I imported into RStudio.
There is a column of data called “Quantity” that contains the quantity of produce that is sold. In RStudio, I run the following command in the console:
summary(farmers$Quantity)
And the following result is returned in the console:
Min. 1st Qu. Median Mean 3rd Qu. Max.
182.0 452.5 782.0 1696.0 969.5 9183.0
I put the exact same command in the R Markdown file as follows:
```{r}
summary(farmers$Quantity)
```
And this error message is returned:
Error in summary(farmers$Quantity) : object ‘farmers’ not found Calls: … withCallingHandler -> withVisible -> eval -> eval -> summary
Execution halted
This is a terribly arcane message that, when translated to English, is saying that the data frame “farmers” could not be found. This is puzzling because in the console RStudio is able to find the data frame. If it works in the console, why not in R Markdown?
The issue is involves the spirit of replicability that is so important to R. The R Markdown file requires to you to show all the steps you took to produce your data, and this includes showing the step where you loaded your data frame.
To fix this problem you first need to, if you have not already, save your data frame as an .Rdata file. With my data frame called “farmers”, that console command is:
save(farmers, file = "farmers.RData")
Second, in your R Markdown file, you need to tell RStudio load that RData file. For me, code is:
```{r}
load("farmers.RData")
```
Press “Knit HTML” and it should now work. RStudio can now find the data frame to produce results from.
One thing to also note is that if you use a package, you also have to load that in your R Markdown file. Again, this goes back to the spirit of replicability and showing your work so that others could rerun the same analysis you did. An example code to load a package would be:
library(gmodels)
If the package “gmodels” was being used.