We were unable to load Disqus. If you are a moderator please see our troubleshooting guide.

Joseph Powers • 4 years ago

Hello Irene, Such a useful blog post! You may want to emphasize that the chunk option `code=readLines("myscript.sql")` will NOT execute in the interactive stage of writing the Rmd when the user clicks "Execute Current Chunk". Chunks with a `code` paramater will only execute when knitting the Rmd file into a report. How do you address this gap in your work flow? Because I assume you want to access the data output of your chunks with a `code` chunk option while iterating on the Rmd file.

Ian Gow • 2 years ago

Nice post. My workflow:

1. Use `dplyr`/`dbplyr` to write SQL queries as `dplyr`.
2. Bring the data into RStudio when necessary by calling `collect()`
3. Do complex manipulations or visualizations of the data in RStudio (often actually running in SQL database).
4. Iterate on the steps above.

Many examples of above [here](https://iangow.github.io/fa.... Faculty, graduate students, and researchers at business schools have access to the "WRDS" PostgreSQL database, so it's a great platform for teaching materials in business.

Maggie • 5 years ago

Thank you for the magic asterisk! I'd probably spent 8 hours trying to figure out a simple way to pass multiple parameters into a query in a sql chunk.

Joseph Powers • 5 years ago

Irene, have you been able to create new database tables from SQL chunks in RStudio? I have found that SQL code that works in other editors does not work from inside SQL chunks in Rmd files. e.g., `CREATE TABLE xyz AS SELECT * FROM mtcars;`

James Rogol • 5 years ago

The `code` argument is a great find - it'll save so much copy-and-paste!

Custom Markdown snippets can save time, too. I've set one up to create a sql chunk with `connection` and `output.var` already created. So simple, yet so helpful.

Irene • 5 years ago

Nice idea! Hadn't thought to do that

Joseph Powers • 5 years ago

From an Rmd chunk, how do you execute SQL scripts saved in a different directory than your Rmd file?

Irene • 5 years ago

You'll need to use the path relative to your Rmd. For example, with given this folder structure:

- storms.sql
- storms.Rproj
- reports/report.Rmd

...you'd need to go up one directory from the report.Rmd to reach the SQL file {sql connection=con, code=readLines("../storms.sql")}.