Software Training Institute in Chennai with 100% Placements – SLA Institute
⭐ Exclusive Summer Courses Offer ⭐ 💰 Flat ₹5,000 - ₹10,000 off on all courses 👨‍👩‍👧 Additional discounts for group enrollments 🎓 100% Placement Support 🏆 90,000+ Students Successfully Placed 🚀 Avail now! Limited seats only!
R Programming Tutorial For Beginners - Softlogic Systems
Share on your Social Media

R Prograamming Tutorial for Beginners

Published On: June 25, 2024

Introduction

Starting with R can feel daunting. Many beginners struggle with the initial setup, understanding the command-line interface, and feeling overwhelmed by the vast ecosystem of packages. You might be asking, “Where do I even begin?”

This R programming tutorial for beginners is designed to tackle these pain points head-on, giving you a smooth, jargon-free introduction to R, RStudio, and the basics of data analysis. We’ll focus on practical, hands-on examples right from the start.

Ready to demystify data science? Check out our comprehensive R Programming Course Syllabus today!

Why Students or Freshers Learn R Programming?

Here are the key reasons why students and freshers should learn R Programming:

  • In-Demand Skills: R is the leading language for statistical computing and is crucial for careers in Data Science, Data Analysis, and Statistical Modeling.
  • Advanced Analysis: It offers a vast ecosystem of packages (like Tidyverse and ggplot2) for complex statistical tests, predictive modeling, and machine learning.
  • Stunning Visualizations: R is renowned for creating high-quality, customized, and beautiful data visualizations and reports, which is essential for communicating insights.
  • Lucrative Career Paths: Proficiency in R opens doors to high-paying roles such as Data Scientist, Statistician, and Quantitative Analyst across finance, healthcare, and academia.
  • Open-Source & Free: It is completely free and supported by a large, active community, making it accessible for learning and professional use without licensing costs.

Ready to ace your first interview? Get our exclusive R Programming Interview Questions and Answers now!

Check your knowledge level with our smart Knowledge Assessment Tool

  • Instant skill evaluation with accurate scoring
  • Identify strengths and learning gaps easily
  • Designed for students and working professionals
  • Smart assessment to guide your career growth

Take Your Eligibility Report Instantly

Step-by-Step R Programming Tutorial for Beginners

Here is the step-by-step R Programming tutorial for beginners! This is designed to take you from a complete beginner to confidently executing basic data analysis tasks. We’ll focus on the essentials, ensuring a smooth and practical learning experience.

Step 1. Installation and Setup

The first hurdle for any beginner is getting the necessary tools installed. R programming is typically done using two main components: the R language itself and RStudio, an excellent Integrated Development Environment (IDE) that makes writing R code much easier.

1.1. Installing R

R is a free, open-source project. You need to install the base language first.

  • Go to CRAN: Navigate to the Comprehensive R Archive Network (CRAN) website.
  • Download: Select the download link for your operating system (Windows, macOS, or Linux).
  • Run Installer: Follow the standard installation prompts. Generally, accepting the default settings is recommended.

1.2. Installing RStudio

RStudio provides a user-friendly interface for R, including a code editor, debugging tools, and better project management.

  • Go to RStudio Website: Go to the RStudio download page.
  • Choose Version: Select the RStudio Desktop (Open Source License) version, which is free.
  • Download and Install: Download the appropriate installer for your system and run it. RStudio will automatically detect your R installation.

1.3. Getting to Know the RStudio Layout

When you open RStudio, you will see four main panels. Understanding their purpose is key to navigating R.

  • Top-Left: Source/Script Editor: This is where you write, edit, and save your R code scripts (files ending in .R). You execute code from here.
  • Bottom-Left: Console: This is where R actually runs your code. You can type commands directly here, and you’ll see the output of the code you run from the Script Editor.
  • Top-Right: Environment/History: The Environment tab shows all the objects (variables, datasets, functions) currently loaded in your R session. The History tab keeps a record of commands you’ve executed.
  • Bottom-Right: Files, Plots, Packages, Help, Viewer: This is a multi-tab panel.
    • Plots: This is where any graphs/ visualizations you create, will appear.
    • Packages: This lists all the installed packages and you can load them from here.
    • Help: Where you can look up documentation for R functions.

Step 2. The Absolute Basics: Running Your First Code

Let’s write and run some basic R code.

2.1 Calculations and Basic Arithmetic

The R Console can act like a powerful calculator. Try typing these directly into the Console and press Enter:

# Addition

10 + 5

# Subtraction

25 – 7

# Multiplication

4 * 6

# Division

100 / 5

# Exponentiation (10 squared)

10^2

2.2. Creating and Assigning Variables

In programming, a variable is a name you give to a value or an object. In R, the most common way to assign a value is using the assignment operator <- (read as “gets”).

Open a new R Script file (File → New File → R Script) in the Source Editor and type this:

# Assigning the value 25 to a variable called ‘my_number’

my_number <- 25

# Assigning a text value (string) to a variable called ‘my_greeting’

my_greeting <- “Hello R World!”

# Performing a calculation using the variable

result <- my_number * 2

# Printing the result to the console

print(result)

To run these lines from the Script Editor: Highlight the lines and press Ctrl+Enter (Windows/Linux) or Cmd+Enter (macOS). You will see the variables appear in the Environment panel.

2.3. Data Types

R handles many types of data. The most common basic types are:

  • Numeric: Real numbers, e.g. 10.5, 55, 1.
  • Integer: Whole numbers. Examples: 5L – note the L to force it to be an integer.
  • Character (String): Text enclosed in quotes, such as “data”, “R is fun”.
  • Logical (Boolean): TRUE or FALSE (all caps).

# Check the type of the variable

typeof(my_number)

typeof(my_greeting)

typeof(TRUE)

Step 3. Working With Vectors

The most fundamental data structure in R is the vector. A vector is an ordered collection of values of the same type.

3.1. Creating a Vector

You use the combine function, c() to create a vector.

# A numeric vector of exam scores

exam_scores <- c(85, 92, 78, 95, 88)

# A character vector of names

student_names <- c(“Alice”, “Bob”, “Charlie”, “David”, “Eve”)

# A logical vector

is_pass <- c(TRUE, TRUE, FALSE, TRUE, FALSE)

print(exam_scores)

3.2 Vector Operations

You can perform calculations on entire vectors simultaneously, which is a powerful feature of R (called vectorization).

# Add 5 points to every score in the vector

adjusted_scores <- exam_scores + 5

print(adjusted_scores)

# Find the average (mean) of the scores

average_score <- mean(exam_scores)

print(average_score)

# Check which scores are greater than 90 (returns a logical vector)

high_scores <- exam_scores > 90

print(high_scores)

3.3. Subsetting Vectors

You can select specific elements from a vector using square brackets []. R uses 1-based indexing, meaning the first element is at position 1.

# Select the third score

third_score <- exam_scores[3]

print(third_score)

# Select the first and last scores

first_and_last <- exam_scores[c(1, 5)]

print(first_and_last)

# Select all elements EXCEPT the second one (using a negative index)

all_but_second <- exam_scores[-2]

print(all_but_second)

Step 4. Fundamentals Data Structure: The Data Frame

While vectors are basic, the data frame is the workhorse of R for data analysis. A data frame is a rectangular table (like a spreadsheet) where each column is a vector of the same length, and each column can be a different data type.

4.1. Creation of a Data Frame

Now, let’s put the vectors we created into one single data frame.

# Ensure all vectors have the same length (5 elements in this case)

students_data <- data.frame(

  Name = student_names,

  Score = exam_scores,

  Passed = is_pass

)

# View the structure and content of the data frame

print(students_data)

str(students_data)

4.2 Examining the Data Frame

Several functions help you quickly grasp a new data frame:

# Display the first 6 rows

head(students_data)

# Display the last 6 rows

tail(students_data)

# Get the dimensions (rows, columns)

dim(students_data)

# Get column names

colnames(students_data)

# A statistical summary of the columns (especially useful for numeric data)

summary(students_data)

4.3. Subsetting a Data Frame

To select columns or rows, you use square brackets with two arguments: [row_index, column_index].

  • Using the $ to select a single column is the most common usage:

# Select the ‘Score’ column (returns a vector)

just_scores <- students_data$Score

print(just_scores)

  • Selecting by Position:

# Select the data from the 4th row, 2nd column

data_point <- students_data[4, 2]

print(data_point)

# Select the first two rows and all columns

first_two_students <- students_data[1:2, ]

print(first_two_students)

# Select all rows, only the ‘Name’ and ‘Passed’ columns

name_and_pass <- students_data[, c(“Name”, “Passed”)]

print(name_and_pass)

Step 5. Installing and Using Packages

The true power of R lies in its packages (libraries). A package is a collection of functions, data, and compiled code in a well-defined format. We will focus on the Tidyverse—a powerful collection of packages for data manipulation and visualization.

5.1. Installing a Package

You only need to install a package once per computer.

# Install the tidyverse package (a collection of packages)

install.packages(“tidyverse”)

5.2. Loading a Package

You need to load a package into your current R session every time you start a new session.

# Load the tidyverse library for use

library(tidyverse)

When you run this, you will see messages in the Console listing the main packages loaded (like dplyr for data manipulation and ggplot2 for plotting).

Step 6. Data Analysis and Visualization with Tidyverse

Now let’s use the powerful dplyr package (part of the Tidyverse) for some common data manipulation tasks.

6.1. Filtering Data (filter())

Filter() The function enables you to choose a subset of rows based on specified conditions.

# Select all students who passed (TRUE)

passed_students <- students_data %>%

  filter(Passed == TRUE)

print(passed_students)

Note: We use the pipe operator %>% (read as “then”). It takes the object on the left (students_data) and passes it as the first argument to the function on the right (filter()). This makes code highly readable.

6.2. Choosing Columns (select())

The select() function allows you to choose which columns to keep.

# Keep only the Name and Score columns

name_score_only <- students_data %>%

  select(Name, Score)

print(name_score_only)

6.3. Creating New Columns (mutate())

The mutate() function adds new columns to a data frame or transforms existing ones.

# Add a new column called ‘Grade’

# Assign ‘A’ if score > 90, otherwise ‘B’

students_with_grade <- students_data %>%

  mutate(Grade = ifelse(Score > 90, “A”, “B”))

print(students_with_grade)

Note: ifelse() is a useful function for conditional assignment.

6.4. Summarising Data (summarise())

The summarise() function collapses a data frame into a single row, calculating summary statistics.

# Calculate the mean score and the count of students

summary_stats <- students_data %>%

  summarise(

    Mean_Score = mean(Score),

    Student_Count = n() # n() counts the number of rows

  )

print(summary_stats)

6.5. Basic Visualization (ggplot2)

ggplot2 is the premier package for visualization in R. It uses a grammar of graphics where you build plots layer by layer.

# Create a simple scatter plot of scores

ggplot(data = students_data, mapping = aes(x = Name, y = Score)) +

  geom_point(color = “blue”, size = 3) +

  labs(title = “Student Exam Scores”, x = “Student Name”, y = “Score”) +

  theme_minimal()

  • ggplot(): Defines the data frame (students_data) and the Aesthetics (aes)—how variables map to visual properties (x and y).
  • geom_point(): Specifies the Geometric Object—in this case, points for a scatter plot.
  • labs(): Adds labels and titles.
  • minimal_theme(): A clean, predefined style is applied.

The resulting plot will appear in the Plots panel of RStudio.

Step 7. Reading Data from Files

In the real world, your data won’t be typed manually; it will come from files. R can easily read many formats, but CSV (Comma Separated Values) is the most common.

7.1. Setting the Working Directory

The working directory is the default location R looks for files to read and saves files to write.

# Check your current working directory

getwd()

# Set a new working directory (replace the path with a folder on your computer)

# setwd(“C:/Users/YourName/Documents/R_Projects”)

7.2. Reading a CSV File

If you have a file named my_data.csv in your working directory, you can read it using a Tidyverse function:

# Use read_csv (part of the readr package, loaded by tidyverse)

# This assumes you have a file named ‘data/iris.csv’ available

# For beginners, you can use a built-in R dataset like ‘iris’ instead of reading a file for practice

# my_real_data <- read_csv(“my_data.csv”)

# Using the built-in ‘iris’ dataset for practice

iris_data <- iris

# Now you can use the Tidyverse functions on it

iris_virginica <- iris_data %>%

  filter(Species == “virginica”) %>%

  summarise(

    Avg_Sepal_Length = mean(Sepal.Length),

    Count = n()

  )

print(iris_virginica)

Step 8. Troubleshooting & Getting Help

One of the biggest obstacles for beginners is getting stuck. Knowing where to look for help is crucial.

R Documentation: If you know the name of a function but not how it works, type a question mark before it in the Console:

# Get help for the mean() function

?mean

# Get help for the filter() function

?filter

Error Messages: Don’t fear error messages! They often tell you exactly what is wrong. Common errors include:

  • object ‘xyz’ not found: You misspelled a variable name or forgot to load a package.
  • Missing ) or “: You have either an incomplete command or missing quotation marks.
  • Package errors: Make sure you run library(package_name) after install.

Search your error message directly on Google. The R community is huge, and almost every problem you encounter has been solved and discussed on various sites like Stack Overflow. Just start your search with “R” and your question (e.g., “R how to filter data frame”).

The next step is to solidify this knowledge through practice. Programming is a skill learned by doing. Ready to put your new skills to the test and tackle real-world coding problems? Tackle our comprehensive R Programming Challenges and Solutions to elevate your expertise!

Real Time Examples for R Programming Tutorial for Learners

Here are some real-time, practical examples perfect for R programming beginners, demonstrating its use in different fields:

Financial Data Analysis: Stock Price Trends

Goal: Read real-time or historical stock price data (e.g., from a CSV file or using a package like quantmod).

R Tasks: 

  • Import the data into a data frame using readr::read_csv(). 
  • Calculate the daily returns and moving averages using dplyr::mutate(). 
  • Visualize the adjusted closing price trend over time with ggplot2 to spot potential buying or selling points. 

Skill Learned: Data import, basic time-series calculation, and trend visualization. 

Public Health & Epidemiology: Disease Outbreak Tracking

Goal: Track and visualize the spread of a simulated disease (e.g., COVID-19 cases). 

R Tasks: 

  • Use dplyr::filter() and dplyr::group_by() to aggregate cases by region or date. 
  • Estimate R-naught (reproduction number) by using statistical functionality. 
  • Create a time-series line plot in ggplot2 showing the daily new cases and comparing regional differences. 

Skills Learned: Data aggregation, epidemiological statistics, and comparative plotting. 

E-commerce Analytics: Customer Segmentation

Goal: Segment sample customer data according to their spending and frequency of purchase. 

R Tasks: 

  • Use dplyr::summarise() and dplyr::group_by() to calculate the Recency, Frequency, and Monetary (RFM) values for each customer ID. 
  • Perform a simple clustering analysis (e.g., using k-means) to assign customers to “High Value,” “Loyal,” or “At Risk” segments. 
  • Visualize the segments using a scatterplot to show how different groups fall in a spending vs. frequency grid. 

Skill Learned: Data summarization, clustering/segmentation, and multi-dimensional visualization.

Ready to turn these examples into a portfolio? Explore our curated R Programming Project Ideas to start building your data science portfolio today!

FAQs About R Programming Tutorial for Beginners

1. How can I learn R programming?

Start by installing R and RStudio. Focus on Tidyverse packages like dplyr and ggplot2 for data manipulation and visualization. Practice with real-world datasets and utilize online tutorials, R programming online courses, and community resources like Stack Overflow.

2. What are the 4 data types in R?

The fundamental atomic data types in R are Logical (TRUE/FALSE), Integer (whole numbers), Numeric (decimal numbers), and Character (text/strings). These types form the basis for complex data structures like vectors and data frames.

3. Is R written in C or C++?

The core base of R is primarily written in C and FORTRAN. However, many high-performance R packages, particularly those focused on speed and computation, heavily utilize C++ (often integrated via the R package Rcpp) for optimized code execution.

4. What is the basic concept of R?

R is a language and environment for statistical computing and graphics. Its basic concept revolves around vectorized operations, where functions operate on entire vectors (or columns in a data frame) at once, making data analysis efficient and concise.

5. Is Python or R harder?

Subjective, but beginners often find R’s syntax (focused on statistics and linear algebra) slightly steeper initially, especially with its unique functions. Python’s general-purpose nature and simpler syntax may feel easier to grasp first, though both require practice.

6. Can I learn R in 3 months?

Yes, you can learn the fundamentals of R and become proficient enough for basic data analysis in 3 months with focused, consistent effort (10-15 hours per week). Mastery in advanced statistical modeling and machine learning will take longer.

7. Is R in high demand?

Yes, R is in high demand, particularly in data science, biostatistics, academia, and quantitative finance roles. Companies value R skills for its powerful statistical capabilities and ability to produce high-quality visualizations and reports. Explore R programming salary for freshers.

8. Is R relevant in 2026?

Yes, R will remain highly relevant in 2026. While Python dominates general-purpose ML, R continues to be the gold standard for deep statistical analysis, biostatistics, and creating reproducible research and reports using tools like R Markdown.

9. Which careers use R?

Careers that heavily use R include Data Scientist, Statistician, Data Analyst, Quantitative Analyst, Biostatistician, and Epidemiologist. These roles rely on R for modeling, reporting, and complex data visualization.

10. What skills do you need to R?

To effectively use R, you need basic statistical knowledge, data manipulation skills (using dplyr), data visualization skills (using ggplot2), and a logical approach to problem-solving and debugging code. 

Conclusion

You’ve successfully completed the first crucial steps in R programming. You’ve mastered the setup, basic syntax, and the fundamental data structures like vectors and data frames. Most importantly, you’ve started using the powerful Tidyverse for data manipulation and visualization. This is just the beginning of your data science adventure! Ready to dive deeper into statistical modeling and machine learning with R? Enroll in our full R Programming Course in Chennai today and become a data expert!

Share on your Social Media
Get Your Instant Job & Placement Eligibility
Report in Just 30 Seconds!
Below 30% - not Eligible (Needs Preparation)
30% – 70% - Partially Eligible (Needs Guidance)
Above 70% - Fully Eligible (Ready to Start)

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.