Setup Code (Click to Expand)
# packages needed to run the code in this section
# install.packages(c("DBI", "ODBC", "dplyr"))
# packages needed to run the code in this section
# install.packages(c("DBI", "ODBC", "dplyr"))
One of the first tasks you will need to do with any analysis is loading in the data. While you may have data from a variety of sources, the most common will be in a SQL database.
Here we will cover how to access a SQL database and extract data in R.
The R packages you need to interact with SQL are:
I won’t import either package here because they are only needed for a handful of functions.
<- DBI::dbConnect(
con ::odbc(),
odbcdriver = 'SQL Server',
server = '{db-server}',
database = '{db-name}',
trustedconnection = TRUE
)
<- DBI::dbGetQuery(
df
con,'SELECT col_1,
col_2,
col_3
FROM db_name.table_name'
)
head(df)
::glimpse(df) dplyr
::write_csv(df, here::here('path-to-save-df', 'df.csv')) readr