Before we begin
Working with data in R; data frames and file paths; mean, SD, median, and quantiles.
We will run a few chunks at a time as we reach each topic in class.
Open BTE3207_Advanced_Biostatistics.Rproj, then open this
week’s .Rmd file. Run the chunks from the top, or click
Knit to make the whole document.
Working with data in R
There are different types of data in R. We will call one value a
data element. In R, even one value is a vector of length 1.
When data elements are gathered (with orders), that chunk of data is
called a vector.
Here are some examples.
Data element
alpha <- 1 # this is data element
alpha # If we call alpha, the computer will display the value assigned to alpha.
## [1] 1
Vector
To assign vector in R, we use c(), with comma
, as separators. For example:
beta <- c(1, 2) # this is a vector
beta
## [1] 1 2
gamma <- c(alpha, beta) # This is also a vector
gamma
## [1] 1 1 2
Remember vectors are ordered.
delta <- c(beta, alpha) # it is still a vector
delta
## [1] 1 2 1
When you call beta in R, it will retrieve
data associated with beta. So, how do we assign
characters (letters or categorical variable)? R recognizes
character values with quotation marks, "". For
instance:
delta_2 <- c("beta", "alpha")
delta_2
## [1] "beta" "alpha"
With quotation marks, the R will recognize inputs as a new character data, not the data we assigned previously.
Data frame
So, what should we do with larger data sets, such as Excel spreadsheets?
Vectors in R can be combined into a data frame, as long as their lengths are the same.
This is called data frame in R, and it can be created using the
data.frame() function.
epsilon <- data.frame(gamma, delta) # This is a data frame
# Note that the lengths of both gamma and delta are the same.
epsilon
Selecting variables (vectors) in data frame
A data frame has columns, where each column represents one variable (vector).
We use the dollar sign $ to select a specific variable from a data frame.
epsilon$gamma
## [1] 1 1 2
epsilon$delta
## [1] 1 2 1
epsilon$gamma returns the exact same vector as just
gamma, which was used for constructing epsilon.
Now, how can we generate a larger dataset for analysis?
Data frame example
We can make data by adding multiple data elements to vectors, and we can bind those vectors to make one dataframe.
subject <- c("Joe", "Trump", "Obama", "George") # Assigning multiple data elements as a vector
height <- c(183, 190, 187, 182)
IsTall <- c("short", "tall", "tall", "short")
example_dataframe <- data.frame(subject, height, IsTall) # Combining 3 vectors into one data frame
example_dataframe # Displaying the example_data frame
Loading Data
However, we won’t be typing all the data manually every time it’s
needed. To save time, we will directly load data frames from our
computer using the read.csv() function for
.csv files. Excel .xlsx files need another
function, such as readxl::read_excel().
Here is an example using systolic blood pressure (SBP) data from NHISS.
dataset_sbp <- read.csv(file = "dataset/sbp_dataset_korea_2013-2014.csv")
reactable::reactable(head(dataset_sbp, 50), sortable = TRUE)
Here, dataset/ is the folder inside our R project. Open
BTE3207_Advanced_Biostatistics.Rproj first, then open this
document. The path is relative to that project folder. The table above
displays the first 50 rows.
When working with data in R, it’s often necessary to load data from
your computer instead of typing everything manually. The most common
file formats for data are .csv (Comma-Separated Values) and
.xlsx (Excel files).
To load a .csv file, we use the read.csv()
function. However, to load the file correctly, you need to know the
file path, which tells R where to find the file on your
computer.
Meanwhile, actually you can download the files at your current working directory with a valid URL for the file as well.
This is optional. The file is already in our dataset/
folder. Run this chunk manually only if you need another copy.
url_link <- "https://raw.githubusercontent.com/minsiksudo/BTE3207_Advanced_Biostatistics/refs/heads/main/dataset/sbp_dataset_korea_2013-2014.csv"
download.file(url = url_link,
destfile = "sbp_dataset_korea_2013-2014.csv") # the name that you want to store the linked file at your computer.
list.files() # This shows all the files in your current working directory
dataset_sbp <- read.csv("sbp_dataset_korea_2013-2014.csv") # as the file is in your current folder, you don't need to specify the path.
Understanding File Paths
A file path is like a map that tells your computer where to find a file. There are two types of file paths:
- Absolute Path: This is the full path from the root
directory (e.g.,
C:/on Windows or/on Mac/Linux) to the file. - Relative Path: This is the path relative to your current working directory in R.
Setting the Working Directory
Opening the .Rproj file sets our working directory to
the project folder. This way, we can use relative paths. If you work
without a project, the examples below show setwd().
#setwd("/Users/username/Documents") # For Mac/Linux - this is example file path
#setwd("C:/Users/username/Documents") # For Windows - this is example file path
You can check your current working directory by using:
getwd()
## [1] "/Volumes/macdrive/Dropbox/10_Inha/50_Lectures/10_BTE3207_Biostats/2026F/scripts/BTE3207_Advanced_Biostatistics"
Example of Loading a CSV File
Here’s how you can load a CSV file into R:
# Example for Mac/Linux
#dataset_sbp <- read.csv(file = "/Users/username/Documents/sbp_dataset.csv")
# Example for Windows
#dataset_sbp <- read.csv(file = "C:/Users/username/Documents/sbp_dataset.csv")
Using the file.choose() Function
If you’re unsure about the file path, R provides a
file.choose() function that opens a file dialog to help you
select the file interactively:
Try using the function after removing the
number sign (#) of the below code
#dataset_sbp <- read.csv(file = file.choose())
This method is platform-independent and can be a helpful alternative if you’re having trouble with file paths.
The data is loaded as shown below. However, since it contains 1
million lines of data, displaying the entire dataset would make this
document too long. Instead, we can use the head() or
tail() functions to view only the first 10 or last 10 rows,
respectively.
head() and tail() Functions
head()
head(dataset_sbp, 10)
tail()
tail(dataset_sbp, 10)
A few more rows
head(dataset_sbp, 20)
nrow(dataset_sbp)
## [1] 1000000
ncol(dataset_sbp)
## [1] 7
This shows (subsets of) gender, age group, SBP, DBP, FBS, DIS, and BMI data for 1,000,000 subjects.
For now, we will use the dollar sign to select one variable from the
data frame. Again, I will use the head() function to check
the first 10 rows of data this time.
head(dataset_sbp$SBP, 10)
## [1] 116 100 100 111 120 115 110 115 130 100
That’s a lot of data!
Basic R Functions for Statistics
Now, let’s use R to calculate summary statistics for this large dataset.
Mean Calculation
The function for calculating the mean is mean().
mean(dataset_sbp$SBP)
## [1] 121.8718
This is the mean value of all the SBP data (1,000,000 rows).
SD Calculation
The function for calculating the standard deviation is
sd().
sd(dataset_sbp$SBP)
## [1] 14.56171
This is the sample standard deviation. R uses n - 1 in
the sample variance calculation.
x <- c(110, 120, 130)
sqrt(sum((x - mean(x))^2) / (length(x) - 1))
## [1] 10
sd(x)
## [1] 10
Median
The function for calculating the median is median().
median(dataset_sbp$SBP)
## [1] 120
Function for Calculating Quantiles: quantile()
The quantile() function can be used to calculate
multiple percentiles at once. Without specifying any percentile, it will
return the 0%, 25%, 50%, 75%, and 100% percentiles.
quantile(dataset_sbp$SBP)
## 0% 25% 50% 75% 100%
## 82 110 120 130 190
Since the output of quantile() contains multiple data
elements, the result is a vector. Conveniently, this
output also includes names. To check the structure of this output, we
can use the str() function.
str(quantile(dataset_sbp$SBP))
## Named num [1:5] 82 110 120 130 190
## - attr(*, "names")= chr [1:5] "0%" "25%" "50%" "75%" ...
The str() function indicates that it is a
named numeric variable.
Quantile() - Continued
But what if we want to find the value at a specific percentile? In that case, we need to provide more information to the function.
These pieces of information are called arguments.
Since functions in R can accept multiple inputs, we separate them
with commas (,).
For example, to calculate the 10th percentile of the SBP dataset:
quantile(x = dataset_sbp$SBP, probs = 0.1)
## 10%
## 103
Using the Question Mark to Explore a Function
As these functions can have multiple arguments, and there are many
packages that can be installed to add new functions to R,
developers provide detailed instructions. You can access this
information by adding a ? before a function name.
?quantile
For some popular functions, details about the arguments
will usually appear in pop-ups. You can use the Tab button
to see what the function can do.
Question
Now, try the same thing with DBP. What are the mean, SD, median, and
the 10th percentile? Use the same functions, but change the variable
after $.
mean(dataset_sbp$DBP)
sd(dataset_sbp$DBP)
median(dataset_sbp$DBP)
quantile(dataset_sbp$DBP, 0.1)
One more thing. SEX is stored as a number in this file,
but it represents categories. Does calculating its mean answer the same
kind of question as calculating mean SBP?
Bibliography
R Core Team (2024). R: A Language and Environment for Statistical Computing. R Foundation for Statistical Computing, Vienna, Austria. https://www.R-project.org/.
Xie Y (2025). knitr: A General-Purpose Package for Dynamic Report Generation in R. R package version 1.50, https://yihui.org/knitr/.
Xie Y (2015). Dynamic Documents with R and knitr, 2nd edition. Chapman and Hall/CRC, Boca Raton, Florida. ISBN 978-1498716963, https://yihui.org/knitr/.
Xie Y (2014). “knitr: A Comprehensive Tool for Reproducible Research in R.” In Stodden V, Leisch F, Peng RD (eds.), Implementing Reproducible Computational Research. Chapman and Hall/CRC. ISBN 978-1466561595.
Allaire J, Xie Y, Dervieux C, McPherson J, Luraschi J, Ushey K, Atkins A, Wickham H, Cheng J, Chang W, Iannone R (2025). rmarkdown: Dynamic Documents for R. R package version 2.30, https://github.com/rstudio/rmarkdown.
Xie Y, Allaire J, Grolemund G (2018). R Markdown: The Definitive Guide. Chapman and Hall/CRC, Boca Raton, Florida. ISBN 9781138359338, https://bookdown.org/yihui/rmarkdown.
Xie Y, Dervieux C, Riederer E (2020). R Markdown Cookbook. Chapman and Hall/CRC, Boca Raton, Florida. ISBN 9780367563837, https://bookdown.org/yihui/rmarkdown-cookbook.
Barnier J (2022). rmdformats: HTML Output Formats and Templates for ‘rmarkdown’ Documents. R package version 1.0.4, https://CRAN.R-project.org/package=rmdformats.
Lin G (2023). reactable: Interactive Data Tables for R. R package version 0.4.4, https://CRAN.R-project.org/package=reactable.