Free R programming tutorials
Learn R for data analysis, statistics and data science
Step-by-step lessons with real, copy-ready code — from your first line of R to dplyr data wrangling and publication-ready ggplot2 charts.
Welcome to Learn-R.org, a free, beginner-friendly place to learn R through clear explanations, practical examples and step-by-step tutorials. Whether you are completely new to programming, studying statistics, conducting academic research, or building skills for data analysis and data science, this guide will help you get started with R and gradually apply it to real problems.
If you are an absolute beginner in R and want to learn R for data analysis or data science from R experts I will strongly suggest you to see this R for Absolute Beginners Course
R is a programming language used to work with data. You can use it to calculate statistics, clean spreadsheets, explore datasets, create charts, test research hypotheses, build predictive models and produce repeatable reports. You do not need to be an experienced programmer to begin. Start with a few simple commands, practise each concept, and then build on what you have learned.
This R tutorial for beginners introduces the language, explains where R is used, and outlines a learning path from basic syntax to data manipulation, visualization, statistical analysis and machine learning. The examples are designed to be understandable even if you have never written code before.
R is a free, open-source programming language and software environment for statistical computing, data analysis and graphics. It helps you work with data systematically: import it, check its quality, summarise important information, investigate patterns, apply statistical methods and communicate your findings. R is used in universities, research organisations, government, healthcare, finance, marketing and many businesses.
Imagine that you have a spreadsheet containing thousands of sales records or survey responses. You could inspect the rows manually, but that becomes slow and error-prone as the dataset grows. With R, you can write a short script to calculate totals, compare groups, identify missing values and create charts. When new data arrives, you can run the script again rather than repeat every step by hand.
R is both a language and an ecosystem. The base installation includes many common operations and statistical methods. Additional packages provide specialised tools for tasks such as data cleaning, visualization, modelling, reporting and interactive applications.
You can begin with a single calculation. In R, type the following command into the console:
2 + 3
R returns [1] 5. The number [1] indicates the position of the first value in the output; the answer is 5. Try changing the numbers or using subtraction, multiplication and division.
# Store values in variables
price <- 50
quantity <- 12
# Calculate total revenue
revenue <- price * quantity
print(revenue)
The assignment operator <- stores a value under a name. Here, R multiplies the price by the quantity and prints 600. Lines beginning with # are comments: they explain the code and are not executed as commands.
One reason to learn R is that the same core skills can be applied in many fields. You might analyse a class survey, investigate a medical study, study economic indicators, evaluate a marketing campaign or explore financial data. The question and dataset change, but the workflow is often similar: understand the data, prepare it, explore it, choose an appropriate method and explain the results.
Data analysis is the process of turning raw data into useful information. Data science can include this work as well as statistical modelling, prediction and more complex computational methods. R supports the main stages of a data workflow:
For example, a data analyst working with online orders might calculate average order value, compare sales across regions, identify seasonal patterns and investigate which product categories are growing. R makes the steps repeatable, so the analysis can be updated when a new month of orders is added.
R is particularly well suited to statistical analysis. It can calculate means, medians, standard deviations, probabilities, confidence intervals and correlations. It also supports hypothesis tests, analysis of variance (ANOVA), linear regression, logistic regression, survival analysis and many specialised methods through packages.
Researchers and analysts use these methods to answer questions such as:
For example, a researcher evaluating a teaching intervention might compare student results before and after the intervention or between suitable comparison groups. The research design, assumptions and data quality should guide the method. Running a statistical test does not, by itself, establish that an intervention caused an observed difference.
R is widely used by students, lecturers and researchers who need transparent, repeatable analysis. It can be useful for undergraduate projects, master's dissertations, doctoral research, journal articles and research reports. Researchers may use R to analyse questionnaire data, test hypotheses, summarise experimental results, model relationships between variables and create publication-ready figures.
For survey research, for example, R can help import responses, recode categories, inspect missing answers, calculate scale scores, examine reliability and fit regression models. For experimental data, it can summarise groups, visualise outcomes and estimate differences with uncertainty intervals. The exact analysis should follow the study's research questions, measurement design and disciplinary standards.
A script also provides a record of the analysis steps. This makes it easier to check calculations, revise a model, reproduce a figure and explain how a result was obtained. Reproducibility still depends on documenting data sources, package versions, exclusions and analytical decisions.
Health researchers use R to study patient outcomes, disease patterns, clinical studies, public-health trends and healthcare service delivery. Depending on the dataset and research question, R can support descriptive summaries, epidemiological analysis, clinical-trial statistics, survival analysis and the visualization of trends over time.
For instance, a public-health analyst could examine how reported cases vary by month and region, while a clinical researcher might study the time until a particular event occurs. Health data requires careful privacy protection, appropriate study design and expert interpretation. An association in observational data does not automatically indicate a cause, and a statistical model should not be treated as a substitute for clinical judgement.
R can be used to analyse economic indicators, investment returns, prices, inflation, employment, business performance and financial time series. Economists may estimate relationships between variables or evaluate policy outcomes. Financial analysts may explore returns and volatility, compare portfolios, study risk measures or model time-dependent data.
In a business setting, R can help answer questions about revenue, profitability, customer behaviour, inventory and operational performance. A retailer might compare monthly sales across branches, investigate changes in average order value or forecast demand. Results should be checked for seasonality, unusual events, data limitations and uncertainty before being used to make decisions.
Marketing teams can use R to understand customer segments, campaign performance, purchase patterns and customer retention. Typical tasks include summarising campaign responses, comparing conversion rates, analysing customer lifetime value, segmenting customers and investigating factors associated with churn.
For example, an analyst might compare the response rate for two email campaigns. A fair comparison needs the group sizes, campaign conditions and relevant context—not just the number of clicks. If customers were not assigned to campaigns randomly, differences may reflect other factors. R helps organise the analysis, but the design determines what conclusions are justified.
Charts can make trends, group differences and relationships easier to understand. R includes basic plotting functions, and the ggplot2 package provides a flexible system for building layered graphics. Common charts include bar charts, histograms, scatterplots, boxplots, line charts and density plots.
Choose the chart based on the question. A line chart can show how a measurement changes over time; a histogram displays the distribution of a numeric variable; a scatterplot helps examine the relationship between two numeric variables; and a boxplot can compare distributions across groups. Clear labels, meaningful units and an appropriate scale are more important than decorative effects.
R supports many machine-learning and predictive-modelling workflows. Depending on the problem, you can fit regression and classification models, group similar observations with clustering, reduce the number of dimensions in a dataset, or evaluate predictions using validation data. Applications include demand forecasting, customer segmentation, risk analysis and estimating the likelihood of an outcome.
For example, a business might use historical customer records to estimate which customers are more likely to cancel a service. A model should be evaluated on data not used to fit it, with metrics suited to the problem. Check for data leakage, imbalance, bias and changing patterns over time. A predictive relationship does not necessarily explain why an outcome occurs.
R is useful for analysing educational results, population statistics, census data, public opinion, social surveys and policy outcomes. Education researchers can compare assessment results and explore factors associated with student performance. Social scientists can examine survey responses and relationships between demographic, behavioural or economic variables. Government and non-profit organisations may use R to summarise service usage, monitor indicators and communicate findings to the public.
In these settings, it is important to explain how the data was collected, who is represented, which observations are missing and what the analysis cannot establish. Responsible interpretation is part of good data analysis.
You can download and use R without purchasing a commercial programming licence. Many packages are freely available, making R accessible to students, teachers, independent researchers and organisations. Check the licence of each package and the usage terms of any dataset or other resource, especially for commercial projects.
R offers a broad collection of statistical functions and packages. If you are studying statistics, economics, psychology, public health, business analytics or data science, learning R can help you connect theoretical concepts with practical analysis. You can calculate a result, inspect the underlying data and produce a graph using the same environment.
When an analysis is written as a script, you can rerun the same steps and update the output when the source data changes. This is useful for monthly reports, research projects and recurring dashboards. Good practice includes using clear file paths, recording data sources, checking package versions and documenting decisions.
Packages extend R's built-in capabilities. Beginners commonly encounter dplyr for data manipulation, ggplot2 for visualization, readr for reading delimited files, readxl for Excel workbooks, and shiny for interactive web applications. You do not need to learn every package at once; choose tools that solve the task you are working on.
R is available for the major desktop operating systems. Many scripts work across systems, although file paths, installed packages and system dependencies may require small changes. RStudio is a popular development environment that makes it easier to write scripts, organise projects, inspect data and view charts.
If you are new to programming, learn R in stages. Practise each topic with small examples before moving on. You do not need to memorise every function: focus on understanding the main concepts, reading error messages and learning how to find help.
Install R, then consider installing RStudio Desktop as an environment for writing and running code. R is the language and runtime; RStudio is an interface that helps you work with it. You can also use R from its console or another compatible editor. Once everything is installed, try a calculation such as 10 + 5.
Variables let you store values and reuse them. Start with numeric values, text strings, logical values, arithmetic operators and comparisons. Learn how to assign values using <- and how to display results.
student_name <- "Amina"
score <- 85
passed <- score >= 50
print(student_name)
print(score)
print(passed)
This example stores a name, a score and the result of a comparison. The expression score >= 50 evaluates to TRUE because the score is at least 50.
A vector stores a sequence of values of the same basic type. A matrix arranges values in rows and columns. A list can contain different kinds of objects, and a data frame stores tabular data in columns that may have different types. Data frames are especially important because many real datasets are organised as tables.
scores <- c(72, 85, 91, 68, 88)
mean(scores)
max(scores)
min(scores)
students <- data.frame(
name = c("Amina", "Bilal", "Sara"),
score = c(82, 76, 94)
)
print(students)
The function c() combines values into a vector. The functions mean(), max() and min() calculate the average, highest and lowest scores. The data frame stores student names alongside their scores.
Functions package instructions into reusable units. Conditions let your program make decisions, while loops repeat a task. These concepts help you move from one-off calculations to more flexible programs. Learn them gradually and practise by changing inputs and checking outputs.
score <- 76
if (score >= 50) {
print("Pass")
} else {
print("Needs more work")
}
The condition checks whether the score is at least 50 and prints the corresponding message. Real grading rules depend on the course or examination, so this is only a simple programming example.
Most useful R projects involve data from a file, database or other source. Learn to import CSV files and Excel workbooks, inspect column names and data types, check ranges, and identify missing values. Before analysis, confirm what each row represents and whether variables have been recorded consistently.
# Read a CSV file in your working directory
df <- read.csv("data.csv")
# Inspect the data
head(df)
str(df)
summary(df)
colSums(is.na(df))
Replace data.csv with the name and path of your file. The commands show the first rows, the structure and data types, summary information and the number of missing values in each column. A file must be available at the path you specify.
Data cleaning may involve selecting columns, filtering rows, arranging records, creating new variables and summarising groups. The dplyr package provides readable functions for these tasks. Learn the key verbs—select(), filter(), mutate(), arrange() and summarise()—and how to combine them with the pipe operator.
Explore the dplyr tutorial for a focused guide to data manipulation.
# Install dplyr once if it is not already installed
# install.packages("dplyr")
library(dplyr)
sales <- data.frame(
region = c("East", "West", "East", "West"),
revenue = c(1200, 900, 1500, 1100)
)
sales %>%
group_by(region) %>%
summarise(total_revenue = sum(revenue), .groups = "drop")
The code groups records by region and calculates total revenue for each region. This is a common operation in sales reporting and business analytics.
Once you can inspect and prepare data, learn how to visualise it. With ggplot2, you specify the data, map variables to visual properties and add a geometry such as points, bars or lines. Start with one clear question per chart, then improve titles, axis labels and legends.
Visit the Learn-R.org tutorials as you progress from R basics to more focused data analysis topics. A dedicated visualization tutorial can help you learn ggplot2 in greater depth.
# A simple chart using base R
months <- c("Jan", "Feb", "Mar", "Apr")
revenue <- c(12000, 14500, 13800, 17200)
plot(revenue, type = "b", xaxt = "n",
xlab = "Month", ylab = "Revenue",
main = "Monthly Revenue")
axis(1, at = 1:4, labels = months)
This example plots four monthly revenue values and labels the horizontal axis with month names. The data are illustrative, not actual business results.
Before applying advanced models, understand distributions, averages, variability, sampling, probability and uncertainty. Learn when the mean or median is appropriate, how outliers affect summaries, and why a sample may not represent an entire population. These ideas help you avoid misleading conclusions.
After learning basic data manipulation and visualization, move to confidence intervals, hypothesis tests, correlation and regression. Understand the research question, assumptions and interpretation before choosing a method. A small p-value is not a measure of effect size or practical importance, and correlation alone does not establish causation.
Choose a question that interests you, find a suitable dataset, record its source and build a complete workflow. Import and inspect the data, clean it, create summaries and charts, apply a suitable method, and write a short explanation of the findings and limitations. A finished project helps you practise the entire process rather than memorising disconnected commands.
Suppose you have examination scores for five students. You can calculate a few useful summaries with only a few lines of R.
scores <- c(72, 85, 91, 68, 88)
mean(scores)
median(scores)
sd(scores)
range(scores)
These commands calculate the mean, median, standard deviation and range. The summaries describe different aspects of the scores: central tendency, spread and the minimum-to-maximum span. For a real analysis, also consider the sample size, distribution and context.
# Assume df is a data frame already loaded into R
head(df)
dim(df)
names(df)
str(df)
summary(df)
colSums(is.na(df))
These commands help you understand the number of rows and columns, the variable names, data types, summary values and missingness. This first inspection often reveals problems that should be addressed before modelling or reporting.
sales <- data.frame(
month = c("Jan", "Feb", "Mar", "Apr"),
revenue = c(12000, 14500, 13800, 17200)
)
total_revenue <- sum(sales$revenue)
average_revenue <- mean(sales$revenue)
print(total_revenue)
print(average_revenue)
This example calculates total and average revenue for four illustrative months. In a larger dataset, you could group records by month, product or region and compare performance across categories.
Suppose a dataset contains sales and advertising expenditure. A scatterplot and a linear regression model can help explore their relationship.
# Assume df contains numeric columns named sales and advertising
plot(df$advertising, df$sales,
xlab = "Advertising expenditure",
ylab = "Sales",
main = "Advertising and Sales")
model <- lm(sales ~ advertising, data = df)
abline(model)
summary(model)
The model estimates a linear association between advertising expenditure and sales. It does not prove that advertising caused a change in sales: pricing, seasonality, distribution and other variables may also affect the outcome. Check assumptions and evaluate whether the model is appropriate for the data.
You can do a great deal with base R, but packages make common tasks easier. A package is a collection of functions, data or documentation that extends R. You normally install a package once and load it in each R session when you need it.
dplyr: select, filter, transform and summarise tabular data. Start with the dplyr tutorial.ggplot2: build layered statistical graphics, including scatterplots, bar charts, histograms and line charts.readr: import common delimited text files such as CSV.readxl: read data from Excel workbooks without requiring Excel to be installed.tidyr: reshape and organise data into a tidy structure.shiny: build interactive web applications and data tools using R.knitr and Quarto: combine code, explanations and outputs in reproducible reports and documents.To install a package, use install.packages("dplyr"), for example. To use it in a session, run library(dplyr). If installation fails, check your internet connection, R version and the error message.
R and Python are both capable tools for data work, and neither is the best choice for every task. R has a strong tradition in statistics, research, exploratory analysis and statistical graphics. Python is a general-purpose language used extensively in automation, software development, data engineering and machine-learning systems. Both languages can clean data, visualise information and fit models.
If your immediate goal is statistical analysis, academic research or learning methods used in your field, R can be an excellent starting point. If you want to build general-purpose applications or work across a broad software stack, Python may be a better first choice. Many analysts eventually use both. Focus first on learning how to ask a question, understand data quality, choose a suitable method and interpret results.
R has a large ecosystem, so memorising every command is unrealistic. Learn the common patterns, practise reading help pages and return to examples when needed. Understanding what a function does is more valuable than remembering every argument.
Do not begin modelling immediately after importing a file. Check column types, missing values, duplicate records, unexpected categories and unusual ranges. Incorrect or inconsistent data can lead to misleading summaries and models.
Run code in small sections. Change a value, predict the result and then execute the command. Read error messages carefully and check object names, brackets, commas and file paths. Small experiments help you build confidence and diagnose problems.
A relationship between two variables does not automatically mean that one causes the other. Consider the study design, possible confounding factors, uncertainty and alternative explanations before making causal claims.
Machine learning is easier to understand after you can import, clean, summarise and visualise data. Build these foundations first, then learn modelling, validation and evaluation methods appropriate to your problem.
You can start learning R with simple calculations, variables and vectors without prior programming experience. Some topics—such as data cleaning, statistical inference and modelling—take more practice. Working through small examples in a sensible order makes the learning process more manageable.
Yes. R is free and open source, and you can learn the fundamentals using free software and practice datasets. Many R packages are also freely available. Check the licence and terms of use for any specific package, dataset or learning resource.
No advanced mathematics is required to begin programming in R. You can learn basic syntax, variables, data frames and charts first. Probability, statistics and other mathematical concepts become more important as you move into inference, regression and machine learning.
R is the programming language and runtime that executes your commands. RStudio is an integrated development environment (IDE) that helps you write and run code, manage projects, inspect data, view plots and access documentation. R can also be used without RStudio.
The time depends on your background, goals and how often you practise. You may learn basic commands in a short period, while becoming confident with data cleaning, statistical analysis and modelling requires continued practice. Set achievable goals, such as completing one topic and one small exercise at a time.
Yes. R is used for data exploration, cleaning, visualization, statistical analysis, predictive modelling and reporting. It is particularly popular in research and statistical work, and its packages support many wider data-science tasks.
Choose based on your goals. R is a strong option for statistics, research and data analysis; Python is widely used for general programming, automation and production software. Both can be valuable, and the analytical skills you develop with one language can transfer to the other.
Yes. Base R can read CSV files using functions such as read.csv(). Packages such as readxl can import Excel workbooks. Always check the imported column types, missing values and data structure before analysing the file.
The best way to learn R is to start small and practise consistently. Begin with calculations, variables and vectors; move on to data frames and functions; then learn to import, inspect and clean real data. After that, practise visualization, descriptive statistics, hypothesis testing and regression. Add packages such as dplyr and ggplot2 when you are ready to solve the next problem.
As you work through this free R programming tutorial, aim to understand both the code and the meaning of the result. Ask a clear question, check the quality of the data, choose an appropriate method and explain the limitations of your findings. These habits are useful whether you are studying for a course, completing a dissertation, working in business analytics or building data-science skills.
Ready to begin? Start with the basics, practise each example in R or RStudio, and continue to focused tutorials such as the dplyr tutorial. Build one small project at a time and use what you learn to answer real questions with data.
Thesis & project help
Stuck on your own data?
Send us your dataset. An R expert will clean, analyse and visualise it — with commented code.
Get a Free Quote →Reply within 24 hours
Popular tutorials
Learning tracks