R for Medical Research: A Step-by-Step Guide to RStudio and Statistical Computing for Social Scientists

Picture this. Your boss gives you an Excel spreadsheet containing 300 patients, a column labeled “DM (Y/N)”, and an order to “do the stats by Friday”. That is when people begin to think about learning R for Medical Research. The good news is that you do not need prior programming experience to get started.The good news is that you need not to grasp any coding. It is free, contains all of the tests you could imagine you might need, and is user-friendly enough to make pretty graphs in a journal. This is the window you will work in: RStudio.

It’s written for medical students, residents, and people who are beginning to do research with no programming experience. We’ll go through:

  •  Installing R and RStudio
  • The problem is getting your Excel or CSV file into R. The issue is how to load your .xls or .csv file into R.
  • When should we use a t-test versus when should we use a chi-square? Regression vs. chi-square? How about a few others?
  •  Simple graphs
  •  The basics of meta-analysis

All jargon is clearly explained in context.

What is R and why use R for medical research?

R is a statistical programming language. It began in the early 1990s at the University of Auckland, by two statisticians, Ross Ihaka and Robert Gentleman. Don’t be intimidated by the term “programming”. In practice, you type in something such as mean(age), press an arrow, and then R returns with the answer.

There is no cost for it. R is an open-source platform, and the source code is made available as well. Why is it so popular with biostatisticians (those who use statistics in medicine and biology)? A few reasons:

  • There’s one for the simple, such as averages, as well as the heavy stuff such as survival analysis.
  • Free add-ons (called packages) that take nearly any special method have been written by people all over the world.
  • You analyze and save your analysis as code. After six months, Reviewer 2 asks you how you determined that number, and you run the script again.
  • R will be useful in clinical trials and in epidemiology and observational studies like cohort and case-control studies (where you observe people but don’t assign treatments).

Yes, novices can do it just fine. You are given a few commands, use them, then a few more.

R vs RStudio: What Is the Difference?

These are easily confused by almost everyone.

Think of a car. The work is done by the engine, called R. RStudio is the dashboard, steering wheel and seats. It’s the place where you can code, read results, view graphs and locate files.

The engine can operate without a steering wheel. An empty dashboard means no one’s traveling anywhere. Yes, R doesn’t require anything below it, but RStudio does require R to be installed below it.

Opening plain R displays the R console. This is a window with a blank look. Type, receive, repeat. RStudio wraps that same console with a script editor, a plot viewer, a file browser and a help tab. (A script is a file with your commands saved in it.)

RStudio Desktop is free. It’s a product of Posit (which became RStudio when it changed its name).

Install R and Set up RStudio

R goes on first. Then RStudio.

Step 1: Install R

  • Head to cran.r-project.org. The Comprehensive R Archive Network or CRAN is where the official repository for R is located.
  • Pick your system:
  •  In Windows, navigate to Download R for Windows, base and then the download link.
  •  Mac: verify the chip. The installers are “arm64” for Apple M-series Macs, and “x86_64” for older Intel Macs.
  • Linux: see the page for your distribution (Ubuntu, for instance).
  • Run the installer. The default options are satisfactory.

Step 2: Install RStudio Desktop

  • Download and install the free version from posit.co/download/rstudio-desktop.
  •  Open it. R is available stand-alone; you don’t need to link anything to get it.

Step 3: Find your way around

RStudio is divided into four panels. The results are shown in the Console, located at the bottom left. The Environment is in the top right and contains all the data files you have loaded. Tabs for Files, Plots, Packages and Help are located at the bottom right. Only the top-left Source panel that is where you write scripts, will appear when you open a script.

Step 4: Try it

  • Click on Menu File > New Project > New Directory. (It’s easier to keep things tidy if there’s only one project per study!)
  • Create a New File > R Script.
  •  Type 2 + 2, then Ctrl + Enter, or Cmd + Enter (Cmd + Enter on a Mac). A 4 should pop up in the Console. 

Congratulations, you have run R code!

The Code Below Illustrates How to Use the R programming Language

Objects store information for R. Consider an object as a labelled box. Use an arrow to fill one, that is, the less-than sign and hyphen:

age <- 45

Now, age is 45 for R.

There are values of various kinds. R categorizes them according to their type:

  • A numeric value such as 120 is a value for systolic blood pressure
  • The character:  text in quotes (“male”)
  • Logical: It has only the values of TRUE or FALSE (diabetic or not).
  • Factor: for categories that have fixed levels (mild, moderate, severe)

Several values of one type make a vector. The c() function is used to glue them together:

sbp <- c(120, 135, 142, 118)

Then there’s the data frame, which essentially is an Excel spreadsheet in R, where each row represents a patient. Age, sex or HbA1c are examples of columns. You’ll use one almost everywhere!

Functions perform the operation. The user types in the input within brackets:

mean(sbp)

Answer: 128.75.

The R package system allows the addition of extra functions via packages, more on which soon.

Instructions on how to import medical research data into R

Your data is likely to be in a spreadsheet like Excel, a CSV or SPSS. CSV is “comma-separated values”, a plain text table with commas separating the columns. Any one of your Excel sheets can be saved as one. Place the file in your project folder, and R will locate it by its name.

CSV:

data <- read.csv(“patients.csv”)

Use the readxl package in R (installed in the next section), with Excel:

library(readxl)

data <- read_excel(“patients.xlsx”, sheet = 1)

SPSS, using haven:

library(haven)

data <- read_sav(“patients.sav”)

Ideally, one row equals one patient, one column equals one variable, and every cell has a single value. Merged cells and color-coding do not exist in R.

  • To view the first 6 rows, run the head(data) command. To view all of the columns and their data type, use the str(data) command.
  •  To view the min, max, mean, and median data for numeric columns, use the summary(data) command.

There’s one potential pitfall: If age is entered as a character, someone entered “45 yrs” or “unknown” in a cell. Blank cells turn into NA (not available). 

Use the word per to count them by column as follows:

colSums(is.na(data))

You can remove all the rows where you have no data, using:

 na.omit(data)

But you are removing patients, and they may not be random. 

Sometimes it’s better not to have missing values only for the calculation at hand:

mean(data$age, na.rm = TRUE)

The dollar sign is used to indicate “the age column in data.

Essential R Packages for Medical Research

There are more than 20,000 free packages on CRAN. You will need about 8, if you start with:

  • tidyverse: A tidyverse package for cleaning and reshape data, including dplyr and ggplot2
  • countrymark: to access country data, whether it is downloadable from a website or already stored in R
  • dplyr: for filtering rows, picking columns, making new variables and summarizing by group
  • ggplot2: for graphs
  •  readxl: for reading in Excel files
  • haven: for reading SPSS, Stata and SAS files
  • survival: time-to-event analysis (time to death, time to relapse), including Kaplan-Meier curves and Cox regression (this one is included with R)
  • Meta  for simple meta-analysis and forest plots
  • Metafor, if more flexibility is required or meta-regression.

For each computer:

install.packages(“readxl”)

Every time you open R, you will load:

library(readxl)

If you forget to load a package, R will tell you that “could not find function. That’s the typical explanation.

Basic statistical Tests Using the R program

Before the tests, three ideas. You’ll see them in almost all outputs.

The p-value is the probability of obtaining a result as large as or larger in magnitude than what you found, assuming that there is no difference. By convention, anything less than 0.05 is “statistically significant.”

A confidence interval (CI) provides a range in which the actual effect is likely to fall. If a 95% CI for a difference does not contain 0 (or 1, if it is a ratio), this matches a significant result.

The normal distribution is the bell curve. Parametric tests assume that your data are reasonably normal; non-parametric tests don’t. Check with a histogram or shapiro.test().

The examples use a data frame named data, with columns named sbp, group, sex and outcome.

The first step is descriptive statistics:

mean(data$sbp); median(data$sbp); sd(data$sbp)

table(data$sex)

The standard deviation (SD) measures the spread of the values. The standard error (SE) gives you an idea of how accurate your mean is. SE is simply SD divided by the square root of the sample size.

A t-test compares two means in roughly normally distributed data:

t.test(sbp ~ group, data = data)

t.test(data$sbp_after, data$sbp_before, paired = TRUE)

Line one is the independent t-test (for two separate groups, e.g., drug versus placebo). Line two is the paired version (the same patients before and after). By default, R runs Welch’s t-test, which doesn’t need equal variances. Read the group means, the p-value and the 95% CI.

To compare proportions (e.g., complications by sex), use the chi-square test or Fisher’s exact test:

chisq.test(table(data$sex, data$outcome))

fisher.test(table(data$sex, data$outcome))

Small sample, with expected cell counts below 5? Use Fisher’s. R displays a warning when chi-square may be off.

For three or more groups, use ANOVA, which requires normal data and similar variance:

summary(aov(sbp ~ group, data = data))

A significant ANOVA only tells you that some group is different. TukeyHSD() will tell you which.

Skewed data with two groups? Use the Wilcoxon rank-sum test (Mann-Whitney U):

wilcox.test(sbp ~ group, data = data)

Correlation tells you if two numeric variables go up and down together. Pearson is for normal data, and Spearman is for skewed data:

cor.test(data$age, data$sbp, method = “spearman”)

The coefficient ranges from -1 to +1, and values around 0 indicate little or no relationship.

Linear regression predicts a number, such as SBP:

summary(lm(sbp ~ age + sex, data = data))

Each coefficient is the change in SBP associated with a one-unit change in that variable, with the remaining variables held constant.

Logistic regression models a dichotomous (yes/no) response coded 0/1:

model <- glm(outcome ~ age + sex, data = data, family = binomial)

exp(coef(model))

exp() converts the output to odds ratios. Over 1 means higher odds. Under 1 means lower odds.

Biostatistics & Data Analysis

Knowing the statistical software is one thing. Knowing how to interpret the results is what makes your research meaningful.

From descriptive statistics and hypothesis testing to regression analysis and interpreting research findings, build the biostatistics skills needed to analyze medical data accurately and confidently. Learn to turn raw research data into meaningful results with AARA.

Explore Biostatistics →

Learning objectives for data visualization in R for clinical research.

Always visualize your data prior to running statistical tests. In ggplot2, charts are constructed sequentially in layers: starting with the dataset, followed by variable mappings, and finishing with geometric shapes. 

library(ggplot2)

plotting a histogram for sbp using the ggplot2 package: ggplot(data, aes(x = sbp)) + geom_histogram()

Replace the final piece with another chart:

  • geom_histogram() to look at the distribution of a single numeric column, your easy way to check for normality (or bits of normality)
  • Compare median and spread between groups using geom_boxplot( aes(x = group, y = sbp) )
  • For a scatter plot of two numeric variables such as age and SBP use geom_point()
  • geom_bar() for counts in categories, such as by sex of patient

Afterwards, run ggsave(“figure1.png”), and it’s yours for your manuscript.

The R software package for Systematic Reviews and Meta-Analysis

A systematic review is a search of all the studies addressing a single question, with a search strategy that was designed beforehand so that it can be done by another person. Then, those studies are pooled together by a meta-analysis, resulting in one overall estimate. R does the pooling. The bulk of the work is provided by two packages: meta, which is more straightforward for those with no previous experience (metabin() for yes/no outcomes, metacont() for continuous outcomes), and metafor, which provides support for more complicated models and meta-regression.

A binary-outcome example with meta:

library(meta)

m <- metabin(event.e, n.e, event.c, n.c, studlab = study, data = studies, sm = “RR”)

forest(m)

funnel(m)

For patients treated, event.e and n.e are events and patients respectively, while for controls, event.c and n.c are events and patients, respectively. sm = “RR” is the risk ratio.

You will come across some of the following terms:

Forest plot: Each study is represented by a square and a line (the study’s CI). The diamond at the bottom is the sum of all the answers.

Funnel plot: Effect size vs. precision. Maybe the small negative studies weren’t published, this would be publication bias (if one side is empty).

Heterogeneity: the extent of the differences among the studies from random error. I² is reported as a percentage, and 75% – 100% is considered considerable by the Cochrane Handbook.

Fixed-effect (common-effect) versus random-effects: the first is based on the idea that there is one true effect for every study, while the second allows the true effect to vary.

Subgroup analysis: The subgroup argument can be used for separate pooled results for, for instance, adults and children.

Systematic Review & Meta-Analysis

Move beyond individual studies. Learn how to synthesize evidence and produce meaningful research.

R offers powerful tools for systematic reviews and meta-analysis, including forest plots, funnel plots, and heterogeneity assessment. Develop the research methodology skills needed to search, evaluate, synthesize, and interpret scientific evidence with confidence.

Explore Systematic Review →

R vs SPSS: Which Is Better for Medical Research?

Many of us were introduced to the point-and-click alternative, SPSS, by IBM. Let’s make an honest comparison.

  •  Money:  R is a free statistical software package. SPSS requires a paid license (may be paid for by your University).
  • Getting started: SPSS triumphs on day one as you select commands by clicking on the menu. R requires you to type commands manually, and that can be difficult for a beginner. 
  •  Methods: Do regular tests on both. New and specialized methods are obtained via packages in R. 
  • Graphs: ggplot2 allows you to modify nearly everything about a figure.
  • Reproducibility: An R script is a complete account of what you have done. You can save syntax in SPSS, but many folks just click.

The advice to medical students: If it is SPSS and it is this week, then use SPSS. If you intend to research over the course of many years, use R. It is offered at no cost in all jobs you’ll ever have, and it goes from a t-test to a meta-analysis without changing programs.

Advantages And Limitations of Using R

The advantages of using R

  • Open source (free), no licence fees to pay
  • 20,000+ packages on CRAN

You can embed code, results and text in one report with R Markdown and Quarto.

The FDA don’t require any specific statistical software; therefore, R can be applied in regulated work.

The limitations of using R

  •  You don’t need any commas; if you use commas, they will give you errors. 
  • On the first reading, error messages seem like riddles (errors are often cryptic and misleading).
  •  Package updates sometimes cause a function change, or old code that worked before updates may not work after them.

Anyone can publish a package, try to stick with popular and well-maintained packages.

Medical Research Skills

Your data tells a story. Learn how to analyze it, interpret it, and present it properly.

Statistical analysis is an essential part of medical research, but choosing the right tests and understanding their results can be challenging. Strengthen your knowledge of biostatistics, data interpretation, and research methodology to produce clearer, more reliable research findings.

Explore Research Courses →

Frequently Asked Questions

Q1. Are there any obstacles to R being free for medical research?

Completely. R, RStudio Desktop and CRAN packages are free for students, academics and industry.

Q2. Is it possible for novice programmers to learn R?

Yes. Most clinicians who use R were new to coding. Begin by importing data and descriptive statistics, and then add one test at a time.

Q3. Which is better than SPSS, R?

On cost, graphs, yes, yes, yes, and reproducible and range of methods, yes. There are many people who begin with SPSS and then progress to R, as SPSS is easier to learn.

Q4. Can R perform meta-analysis?

Yes. It can perform meta-analysis and meta-for-all effects, measure heterogeneity and draw forest and funnel plots.

Q5. What are the best R packages for clinical research?

These include the packages tidyverse (dplyr and ggplot2 are included), readxl, haven and survival. Include meta or metafor for systematic reviews.

Q6. Does R have clinical trials?

It is. The FDA doesn’t specify which software to use, and the R Consortium has submitted R-only pilot cases to the FDA.

Having trouble getting started on your own data set? The American Academy of Research and Academics (AARA) helps medical students and researchers with statistics, systematic reviews and meta-analysis. Go through the process of writing a paper with AARA and learn from those who have been there before, from raw data to a published paper.

Disclaimer

Articles published by American Academy of Research & Academics are prepared by our team using information from direct experience, publicly available resources, and educational references. AI tools may be used to assist with drafting, proofreading, and formatting; however, all content undergoes review and approval before publication. The information provided is intended for educational purposes only. Requirements, policies, and processes may change over time. Readers should consult official sources for the most current information.

Facebook
Twitter
LinkedIn
Email
0

No products in the basket.