Introduction to R: Part I

LMU Open Science Center

03/08/2026

Licence and citation

Creative Commons Attribution 4.0 SA

This work was originally created by Nicklas Hafiz and is licenced under a CC-BY-SA 4.0 Creative Commons Attribution 4.0 SA International License. It permits unrestricted re-use, distribution, and reproduction in any medium, provided the original work is properly cited. If you remix, transform, or build upon the material, you must distribute your contributions under the same license as the original. Code snippets are dedicated to the public domain and licenced under a CC0 1.0 Creative Commons Universal Licence.

His work was subsequently adapted by Caterina Luz Sanchez Steinhagen, Tejaswini Sharma, David Rieger, Elizabeth Waterfield, Sarah von Grebmer zu Wolfsthurn, and Sara Lil Middleton.

Please cite as ADD ZENODO REPO.

Contribution statement

Creator: Sanchez Steinhagen, Caterina Luz (orcid logo 0009-0006-4783-1110)

Creator: Sharma, Tejaswini (orcid logo 0000-0000-0000-0000)

Creator: Waterfield, Elizabeth (orcid logo 0009-0006-3725-6730)

Creator: Rieger, David (orcid logo 0009-0004-3701-3101)

Reviewer: Von Grebmer zu Wolfsthurn, Sarah (orcid logo 0000-0002-6413-3895)

Reviewer: Middleton, Sara Lil (orcid logo 0000-0002-6413-3895)

Prerequisites - CHECK versions

Important

Before completing this submodule, please carefully read about the prerequisites.

Prerequisite Description Where to find it
RStudio installed Version Version 2026.04.0+526 or higher Download
R installed Version 4.5.2 or higher Download
Accessibility sheet for computers Fundamentals of computer literacy Download

Before we start: Survey time!


Let us find out where are you at!

What is your level of familiarity with R and RStudio?

  1. I have never heard of it before

  2. I have heard of it but have never worked with it

  3. I have basic understanding and experience with it

  4. I am very familiar and have worked with it extensively

On a scale of 1–5, how intimidated do you feel by programming or coding (e.g., R/RStudio)?
(1 = Not intimidated at all, 5 = Very intimidated)

  1. 1

  2. 2

  3. 3

  4. 4

  5. 5

Have you used any programming language (R, Python, JavaScript, C) before?

  1. No, never

  2. Yes, a little (e.g., basic commands)

  3. Yes, moderately (e.g., small projects)

  4. Yes, extensively (e.g., on an almost daily basis)

Discussion of survey results


What do we see in the results?

Learning goals

  • To navigate the RStudio interface (Console, Environment, Script, and Output panes).
  • To differentiate between basic data types in R (numeric, character, logical, integer) and how they are used.
  • To execute operations in the Console and R Script using appropriate operators.
  • To assign and re-assign values, vectors, and lists to objects.
  • To specify arguments within functions to modify how the function produces its output.
  • To index dataframes to access and retrieve specific information.

Key terms and definitions

You might see some words for the first time or some familiar words used in a different way. What do you associate with the terms below?

  • RStudio
  • R command
  • Run
  • Comment
  • Operator
  • Operation

Key terms and definitions

  • RStudio: A program that provides an easy-to-use interface for writing and running R code.
  • R command: A line of code that tells R to do something.
  • Run: To execute an R command so that R carries out the instruction and shows the result.
  • Comment: Text in your code (starting with #) that R ignores. You can use this function to explain what the code does or make notes throughout your work.
  • Operator: A symbol (such as +, -, *, <, or ==) that tells R to perform a specific action.
  • Operation: The action performed using one or more operators on data or values.

What is R?

R (https://www.r-project.org/) is an free and open source programming language

  • Originally designed by statisticians for statisticians
  • Wide range of applications: data manipulation, visualization, interactive web applications, generation of full manuscripts and reports

Why R?

  • Knowledge of statistical software like R is useful when conducting quantitative research
  • Has a large online support community
  • Provides freely available resources

The RStudio environment

Open RStudio and check if you can see everything that’s on the slide.


(You might only see three panes on your screen)

Mathematical operations

Symbol Operation
+ Addition
- Subtraction
* Multiplication
/ Division
^ Exponentiation
sqrt() Square Root
log() (Natural) Logarithm

Practical exercise 1

Using the table on the previous slide, run the following math operations directly in the Console of RStudio.

Let’s use the Console!

You can run code from the Console by typing in the Console and then pressing Enter on your keyboard.

The R script

An R script is a text file containing your R commands.

  • It is an easy way to save and share code

  • You can run code from an R script by:

    • Pressing Ctrl + Enter (Windows) OR Command + Enter on a (Mac) on the keyboard
    • click on Run
  • You can also add comments or notes to your code by using #

# Here is an example of using a comment 
# sum up two numbers 
4+5
[1] 9

Creating a new R script

Saving an R script

Step 1: On your device

  • Decide where this R script should go
  • Create a new folder

Step 2: In RStudio

  • After making a new R script, click on File → then click Save As...
  • → Name the file → then choose the designated folder
  • → Click Save

Practical exercise 2

# This is my practice R Script

Logical comparisons

With R, you can also:

  • Check if two numbers are equal or unequal

  • Check if a number is larger or smaller than another number

# Example 1:
49 == 50
[1] FALSE
# Example 2:
49 < 50 
[1] TRUE
  • R returns a logical value:

    • TRUE or FALSE

Logical comparisons - operators

Symbol Operation
== Equals
!= Not Equal
> and < Greater and Lesser Than
>= and <= Greater Than or Equal / Less Than or Equal
& logical AND
| logical OR
! logical NOT

Practical exercise 3

TRUE or FALSE?

(36 + 5)> 40

(4 == 5) | (25 > 17)

(5 == (2 + 3)) & (7 >= 8)

Data types

Data types define what kind of values you are working with

Data types

  • These determine how R stores and processes data
  • Data types can show different behavior across different operations
Examples:
  
5        # number (integer)
3.14     # number (numeric)

"hello"  # character
factor("brown")  # factor

TRUE     # logical

Data types: Operations

Can R perform the same operation on different data types?

  • Two numeric variables can be summed up:
4 + 5
[1] 9
  • A numeric and a character variable cannot be summed up:
4 + "5"
Error in `4 + "5"`:
! non-numeric argument to binary operator

Objects and assignment

Objects and assignment

Everything in R is an object, and oftentimes, we want to work with an object repeatedly.

  • Assign a value to an object using the assignment arrow <-
x <- 1
y <- 2

# The example assigns the value 1 to the object "x" 
# and the value 2 to the object "y"

The assignment arrow points to the object

Take note of the order: we put the variable or object name first, then the assignment arrow <-, and lastly the number or value. The arrow should be pointing the object- it would not work if you put 1 <- x

Objects and assignment

The object then appears in the Environment pane (top right pane).

Environment Pane Screenshot with x and y as objects

Practical exercise 4

Try following the example and create your objects!

Objects and assignments

Okay, I made objects… what now?

  • Assigning objects helps organize your values
  • Call on them and use specific objects in new operations
x <- 1
y <- 2

# In a previous slide, we assigned values to the objects

# Now, let's call on the objects and add them together
x + y
[1] 3

Practical exercise 5

Let’s use the objects in a new operation:

x + y

Object reassignment

When you reuse an object name and assign it a new value, R overwrites the previous value.

Functions

What is a function?

  • A function is a reusable block of code that performs a specific task.
  • You provide input values (arguments), and R returns an output based on internal operations.
  • Analogous to a mathematical function:
    • If f(x) = 2 * x, then inputting x = 3 returns 6.
  • Every function has a unique name, followed by parentheses (), such as sum().
# Example of a function taking multiple inputs
sum(1, 2, 3, 4)

The c() function

  • Group items with the c() function to manipulate multiple items at once.
# Example 1: Combine four numbers into one object
age <- c(19, 20, 21)

# Now we can apply a function to the entire group
sum(age)
[1] 60
# Example 2: Combine four character values into one object
food <- c("Pizza", "Pasta", "Burger", "Pasta")

# Now we can organize all the items in this object in a frequency table
table(food)
food
Burger  Pasta  Pizza 
     1      2      1 

Common built-in functions: Numeric

R comes with many built-in numeric functions:

Function What it does
sum() Adds all values together
mean() Calculates the arithmetic mean (average)
sd() Calculates the standard deviation
exp() Calculates the exponential function (\(e^x\))
round() Rounds a number

Practical exercise 6

Common built-in functions: Character

R also comes with many built-in character functions:

Function What it does
sort() Sort values in alphabetical order
unique() Shows the unique values in the set
table() Counts the values in a table
toupper() Transforms all the letters to uppercase
tolower() Transforms all the letters to lowercase

Function arguments

Most functions take multiple arguments (inputs).

  • Arguments are the pieces of information a function needs to carry out an operation.
  • Different functions expect different types and numbers of arguments, and the output of a function often depends on the arguments that are supplied.
  • It might look something like this:
    function_name(argument1 = x, argument2 = y)

Do all functions need multiple arguments?

No, not all functions need multiple arguments, but for some, it is required.

Function arguments

Example: The round() function

  • This function uses two arguments: It approximates a number (x) to a specified amount of decimal places (digits).
  • You can provide arguments by position or by name.
# By position (R assumes the first number is x, the second is digits)
round(3.14159, 2)

# By name (explicitly telling R which argument is which)
round(x = 3.14159, digits = 2)

Naming your arguments makes your code easier to read!

If you name the arguments (using the names “x” and “digits”), the order does not matter: round(digits = 2, x = 3.14159) works identically.

Practical exercise 7

Ignoring the digits argument

If you are curious, try running the round() function without specifying the digits = argument. What happens? Why might that be?

Pre-break quiz

1. What does the # symbol do in R?

  1. Runs the code
  2. Creates a variable
  3. Starts a comment
  4. Multiplies numbers

2. What happens when you “run” code in R?

  1. The code is deleted
  2. R executes the command
  3. The code becomes a comment
  4. RStudio closes automatically

3. What will R return for this comparison?

49 < 50

  1. TRUE
  2. FALSE
  3. 49
  4. ERROR

4. Which of the following is a character value in R?

  1. TRUE
  2. 5
  3. “hello”
  4. 4.2

5. Why does the following produce an error?

4 + "five"

  1. “five” is a logical value
  2. The quotation marks are incorrect
  3. 4 is not numeric
  4. R cannot numerically add different data types together

Break! 15 minutes

Post-break quiz discussion


What do we see in the results?

The Help function

Do I have to memorize all of the functions and arguments?

  • No!
    • There is no need to memorize functions and their arguments.
    • You will remember the ones you use frequently through practice.
  • When you need to understand how a function works, what inputs it needs, or what its defaults are, you can consult the Help Function.

How to access Help in R

There are two main ways to look up a function.

Method 1: Using the Console

  • Type a question mark ? into the console immediately followed by the function name and press Enter.
# Example: Getting help with using the round() function
?round

How to access Help in R

Method 2: Using the Help Tab

  • Navigate to the Help tab in the bottom right pane of RStudio and type the function name into the search bar.

Reading the documentation

Help pages can look intimidating, but you only need to focus on a few key sections:

  • Description: A brief summary of what the function does.
  • Usage: Shows the function with all arguments. This is where you see default values.
  • Arguments: Detailed explanations of what each input to the function should look like.

Reading the documentation

Example: For the sort() function we can see that it can also use character vectors or values as input and orders them.

Practical exercise 8

c("Tim", "Tom", "Anna", "Pizza", "Burger", "Pasta")

Is reverse alphabetical order increasing or decreasing?

Reverse alphabetical order means arranging items from Z to A. This means that the order is decreasing.

Vectors, lists, and data frames

Data structures in R

  • Collections of values are called data

  • R provides ways to store data in different data structures:

    • Vectors
    • Lists
    • Dataframes

Vectors

What does a vector do? Stores multiple values in an object.

  • It is a one-dimensional collection of data
  • Useful for storing scores, ages, measurements, names, and more

Example:

scores <- c(75, 82, 91, 68)

Vectors and data type

What do you notice about the values in the vector stored in scores? All values in a vector should be of the same data type.

Practical exercise 9

Character data type

Reminder: character data types need to be wrapped in quotation marks " ".

Lists

What does a list do? Stores different types of data together.

  • It is also one-dimensional
  • But, unlike vectors, it can contain different data types (e.g., numeric, character…)

Example for a list:

student <- list("Alex", 21, TRUE)

Dataframes

What does a dataframe do? Stores data in rows and columns.

  • It is two-dimensional
  • Rows represent observations, columns represent variables
Name Age Food
Tim 19 Pizza
Tom 20 Pizza
Anna 21 Pasta

Look familiar?

Think of a dataframe like a spreadsheet. The top row is the heading and the information below (within each column) is the observation corresponding to the heading.

Practical exercise 10

Create a dataframe with the data.frame() function

people_data <- data.frame(name, age, food)


Indexing

What does indexing do? Allows us to access specific parts of our data, such as:

  • Select individual or multiple values
  • Access rows and columns in a dataframe

Indexing vectors

Each element in a vector has a position.

age <- c(19, 20, 21)
Position 1 2 3
Value 19 20 21

Indexing vectors

Selecting individual values

  • Use [ ] to call on a value by its position
# Example 1: Calling on the value in position 1 
age[1]
[1] 19
# Example 2: Calling on the value in position 3
age[3]
[1] 21

Indexing vectors

Selecting multiple values

You can retrieve more than one value at once.

age[c(1,3)]
[1] 19 21

You can also select a range:

age[1:3]
[1] 19 20 21

Indexing dataframes

Accessing rows and columns in a dataframe

  • You can call on values directly from the row and column of data frames.

  • To use indexing, use [ ] and follow this general format:

    • dataframe[row,column]
# Example 1: Calling the value in row 1, column 1
people_data[1, 1]
[1] "Tim"
# Example 2: Calling the value in row 3, column 2
people_data[3, 2]
[1] 21

Accessing columns by name

Calling values by using just numbers can get confusing.

Luckily, there is a way to call on the values by column name using the $ operator: dataframe$column_name

  • Use it to retrieve all values from that specific column
  • It is easier to read than using column numbers
# Example: Calling on the "name" column within the "people_data" data frame

people_data$name
[1] "Tim"  "Tom"  "Anna"

Combining $ and []

Look at the following example to see how $ and [ ] can be used together:

people_data$food[3]
[1] "Pasta"

What does this do?

  1. $ selects the food column in the people_data data frame
  2. [] gives you the third value

Practical exercise 11

Use $ and [] accordingly to retrieve the following information from the the people_data data frame:

Wrapping Up

Looking into the future

  1. Take a minute to think about the following questions, first for yourself, then in a pair:
  • Can you identify some practical benefits of using R/RStudio?

  • What obstacles do you anticipate in using it consistently?

  • How can R/RStudio support you in your upcoming projects?

  1. Share your thoughts with the group.

Assignment: Consolidating what you learned

Create a short R script that builds on what was covered today

  1. Assign at least two objects, for example numbers or words.
  2. Create at least one vector using c() and assign it to an object.
  3. Perform at least one mathematical operation using an object with numerical values. Use at least one built-in function, such as sum(), mean(), length(), sort(), or table().
  4. Use at least one logical comparison to check a condition.
  5. Practice indexing by retrieving one specific value from a vector using [].
  6. Include clear comments using # to explain each step.

Self-Assessment

Use this assignment to assess your learning of, and progress with, R/RStudio; reflect on any challenges you faced and how you overcame them.

Take-home messages

  • R → your go-to tool for data analysis and quantitative research.
  • RStudio interface → helps you organize code, outputs, and data efficiently.
  • Writing and saving R scripts ensures your work is reproducible and well-documented.

Learning goals: Check-In

Where are we at?

  • To navigate the RStudio interface (Console, Environment, Script, and Output panes) ✅
  • To differentiate between basic data types in R (numeric, character, logical, integer) and how they are used ✅
  • To execute operations in the R using appropriate operators ✅
  • To assign and re-assign values, vectors, and lists to objects ✅
  • To specify arguments within functions to modify how the function produces its output ✅
  • To index dataframes to access and retrieve specific information ✅

To conclude: Survey time!

1. On a scale of 1–5, how intimidated do you feel by programming or coding (e.g., R/RStudio) after completing this session? (1 = Not intimidated at all, 5 = Very intimidated)

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5

2. How confident do you feel using the RStudio environment after this session?

  1. Not confident at all
  2. Slightly confident
  3. Moderately confident
  4. Very confident
  5. Extremely confident

3. How comfortable do you feel about using R and RStudio for mathematical operations?

  1. Not comfortable at all
  2. Slightly comfortable
  3. Moderately comfortable
  4. Very comfortable
  5. Extremely comfortable

3. How comfortable do you feel using R objects (e.g., vectors and data frames) to organize and manipulate your research data?

  1. Not comfortable at all
  2. Slightly comfortable
  3. Moderately comfortable
  4. Very comfortable
  5. Extremely comfortable

3. What part of the lesson, if any, still feels confusing or unclear?

4. Was there a practical exercise or example that helped your understanding the most? Why?

Discussion of survey results


What do we see in the results?

Thanks!

See you next time!

Practical exercise 1: Solutions

12+17
[1] 29
218/3
[1] 72.66667
357^2
[1] 127449

Practical exercise 2: Solutions

(36 + 5)> 40
[1] TRUE
(4 == 5) | (25 > 17)
[1] TRUE
(5 == (2 + 3)) & (7 >= 8)
[1] FALSE

Practical exercise 6 & 7: Solutions

# Create a vector and assign it to "numbers"
numbers <- c(4.4, 14, 5.26, 26)

# Try out sum(), mean(), and sd()
sum(numbers)
mean(numbers)
sd(numbers)

# Assign the number to "my_number"
my_number <- 2.4637

# Try out exp() and round()
round(my_number)
round(x = my_number, digits = 3)

Practical exercise 8: Solutions

sort(c("Tim", "Tom", "Anna", "Pizza", "Burger", "Pasta"), decreasing = TRUE)
[1] "Tom"    "Tim"    "Pizza"  "Pasta"  "Burger" "Anna"  

Practical exercise 9: Solutions

age <- c(19, 20, 21)

name <- c("Tim", "Tom", "Anna")

food <- c("Pizza", "Burger", "Pasta")

Practical exercise 10: Solutions

people_data <- data.frame(name, age, food)

people_data
  name age   food
1  Tim  19  Pizza
2  Tom  20 Burger
3 Anna  21  Pasta

Practical exercise 11: Solutions

people_data$name[1]
[1] "Tim"
people_data$age[2]
[1] 20
people_data$food[3]
[1] "Pasta"

Additional resources