Session 1: Introduction to R and RStudio

Bella Ratmelia & Wei Xia

Welcome!

Preamble - introductions

  • About Bella:

    • Senior Librarian, Research & Data Services team, SMU Libraries.

    • Have been with SMU since the pandemic era (2021), I have been doing this workshop since Aug 2023.

  • About Wei:

    • Principal Librarian, Instruction and Learning Services, SMU Libraries.

    • Have been with SMU over 17 years. This is my 3rd run of R workshops!

Preamble - About this workshop

  • Live-coding format; code along with us!

  • Goal of workshop: to give you enough fundamentals (at least to the point that ChatGPT can’t bluff you so easily) and confidence to explore R on your own.

  • Don’t be afraid to ask for help! We are all here to learn.

  • Raise your hands if you need help. One of us will come to you.

The outline for these workshops

The workshops are structured to follow this workflow when dealing with data

The outline for Introductory R for Social Science series

  1. Import data into R, which means take data (stored in a file, via API, etc) and load it into a dataframe in R
  2. Tidy the imported data.
    • Tidy = storing it in a consistent form that matches the semantics of the dataset.
    • Tidy data = each column is a variable, each row is an observation
  3. Once a data is tidy, we can transform it. Transformation includes:
    • narrowing in on observations of interest (like all people in one city or all data from the last year)
    • creating new variables that are functions of existing variables (like computing speed from distance and time)
    • calculating a set of summary statistics (like counts or means).
  4. Once we have tidy data with the info we need, we can visualize it and model it.
  5. Communicate the result. It doesn’t matter how well your models and visualization have led you to understand the data unless you can also communicate your results to others.

Today’s plan

  • R and Rstudio
  • Before coding
  • R Objects and Values
  • Data types
  • Functions and packages
  • Data structures
  • Exploring datasets
  • Trouble shooting tips
  • Recap & feedback

What is R? What is R Studio?

R: R is an open-source programming language that was developed for statistical analysis and visualization. Community share R codes and create shortcuts.

RStudio: The R software environment i.e. RStudio is where we use to interact more easily with R language and scripts.

You will need to install both for this workshop. Go to https://posit.co/download/rstudio-desktop to download and install both if you have not done so. Remember: Install R firstly and then RStudio.

Check out the course website for a step-by-step guide.

A Tour of RStudio

Firstly, we need to be comfortable with the RStudio interface. We will use the RStudio to write code, navigate the files on our computer, inspect the variables we create, and visualize the plots we generate.

R Studio layout

Before Coding

  • Creating projects
  • Creating folders and files

Creating the project for this workshop

  1. Go to File > New project. Choose New directory, then New project

  2. Enter intro-r-socsci as the name for this new folder (or “directory”) and choose where you want to put this folder, e.g. Desktop or Documents if you are on Windows. This will be your working directory for the rest of the workshop!

Projects will handle the working directory for you, ensuring that you’re in the correct folder as you continue your project.

Creating folders inside our working directory

Create the following three folders:

  • data - we will save our raw data here. It’s best practice to keep the data here untouched.

  • data-output - if we need to modify raw data, store the modified version here.

  • fig-output - we will save all the graphics we created here!

Note about file names and locations

  • if possible, don’t put your R projects inside your OneDrive folder as that may cause issues sometimes.

  • Folder/file names should avoid spaces, symbols, and special characters. Prefer folder/file names that are all in lower case.

Let’s Code!

  • New script: File > New File > R script
  • Run a line: Ctrl + Enter (Windows) or Cmd + Enter (Mac)
  • Save often! RStudio does not autosave

R Objects and Values

In this line of code:

country_name <- "Singapore"
  • "Singapore" is a value. This can be either a character, numeric, or boolean data type. (more on this soon)

  • country_name is the object where we store this value. This is so that we can keep this value to be used later.

  • <- is the assignment operator to assign the value to the object.

    • You can also use =, but generally in R, <- is the convention.
    • Keyboard shortcut: Alt + - in Windows (Option + - in Mac)
  • Object names: no leading numbers, no spaces, case-sensitive

Refresher: Data Types

  • Non-Continuous Data

    • Nominal/Categorical: Non-ordered, non-numerical data, used to represent qualitative attribute.

      • Example: nationality, neighborhood, employment status
    • Ordinal: Ordered non-numerical data.

      • Example: Nutri-grade ratings, frequency of exercise (daily, weekly, bi-weekly)
    • Discrete: Numerical data that can only take specific value (usually integers)

      • Example: Shoe size, clothing size
    • Binary: Nominal data with only two possible outcome

      • Example: pass/fail, yes/no, survive/not survive
  • Continuous Data

    • Interval: Numerical data that can take any value within a range. It does not have a “true zero”.

      • Example: Celsius scale. Temperature of 0 C does not represent absence of heat.
    • Ratio: Numerical data that can take any value within a range. it has a “true zero”.

      • Example: Annual income. Annual income of 0 represents no income.

Data Types in R

The four basic data types are characters, numeric, boolean, and integer. Let’s look at examples using our WVS survey variables:

country_code <- "IDN" # Character
life_satisfaction <- 8.5 # Numeric (also sometimes called Double)
is_religious <- TRUE # Boolean/Logical (TRUE/FALSE). case sensitive
birth_year <- 1990L # Integer (whole numbers)
  • To include comments in the code, use the # character.

  • Anything to the right of the # sign and up to the end of the line is treated as a comment and is ignored by R when executing.

  • Good practice to make notes and explain the codes.

Checking data type of a variable

You can use str or typeof to check the data type of an R object.

typeof(country_code)
[1] "character"
str(is_religious) 
 logi TRUE

str returns both data type and value.

Arithmetic operations in R

You can do arithmetic operations in R. For example, let’s calculate average satisfaction scores:

(8 + 7 + 9) / 3  # Average of three satisfaction scores
[1] 8
2025 - 1990  # Calculate age from birth year
[1] 35

Boolean operations in R - Simple TRUE/FALSE statements

Boolean operations in R are useful for filtering survey data. Before that, let’s look at how R evaluates simple TRUE/FALSE statements

Is life_satisfaction greater than 8?

life_satisfaction <- 8.5 # assign a value of 8.5 to life_satisfaction
life_satisfaction > 8  
[1] TRUE

Is the country Indonesia?

country_code == "IDN"
[1] TRUE

Is the country NOT Indonesia?

country_code != "IDN"
[1] FALSE

Boolean operations in R - AND operator

Sometimes, we may have multiple statements to evaluate. This is where the Boolean Operators will come handy.

AND operations (both conditions must be TRUE). In R, it is represented by ampersand &

Is the country Malaysia AND is the life satisfaction more than 8?

(country_code == "MYS") & (life_satisfaction > 8)
[1] FALSE

country_code == "MYS" is FALSE while life_satisfaction > 8 is TRUE

The whole statement will return FALSE because not all conditions TRUE.

Boolean operations in R - OR operator

OR operations (at least one condition must be TRUE). In R, it is represented by pipe symbol |

Is the country Malaysia OR is the life satisfaction more than 8?

(country_code == "MYS") | (life_satisfaction > 8)
[1] TRUE

As long as one condition is met, this will be TRUE.

Functions in R

  • A function is like a recipe in cooking.

  • It takes some ingredients (inputs) and uses a set of instructions to produce a result (output).

  • In R, a function is a pre-written set of recipes/instructions that performs a specific task. Function name will always be followed by round brackets ()

Example: round() function in R will round up numbers.

round(3.1415926)
[1] 3
  • round() is the “recipe”, while 3.1415926 is the “ingredients”

Saving the result to an object:

rounded_pi <- round(3.1415926)
print(rounded_pi)
[1] 3

Functions with Arguments in R

Arguments are the ingredients you give a function. Some are required, others are optional (they have default values).

Think of a bubble tea order as a function:

# not a real R function, just an analogy!
bubble_tea(tea = "oolong", milk = TRUE, topping = "pearls")

bubble_tea(tea = "oolong") # milk and pearls are included by default

What happens if I leave out tea?

round() works the same way:

round(3.1415926, digits = 2)
[1] 3.14
  • 3.1415926 is the required argument (if this is not provided, the function will not run)

  • digits is an optional argument specifying how many decimal places to round to (the default is 0)

How do I find out more about a particular function?

You can call the help page / vignette in R by prepending ? to the function name.

E.g. if you want to find out more about the round function, you can run ?round in your R console (bottom left panel)

Data Structures in R

We will start with exploring 3 basic types of data structures in R:

  1. Vector - can hold multiple values in a single variable/object.

  2. Factor - Special data structure in R to handle categorical variables.

  3. Data frame - De facto data structure for tabular data in R, and what we use for data processing, plotting, and statistics.

Other types (but we will not be covering these in this workshop):

  • Lists: A type of recursive vector

  • Matrices: A collection of elements of the same type in rows and columns

Data Structures in R - visualized

Data Structures in R: Vectors

Think of vectors as a column in a dataset. It is the most common and basic data structure in R. (pretty much the workhorse of R!)

  • A vector can only contain 1 data type.

  • Vector can be created with c() function.

  • Can add, remove, or change values in a vector.

  • Inspect vectors: typeof(), str(), length()

countries <- c("Hong Kong SAR", "Indonesia", "Malaysia", "Hong Kong SAR", "Turkey")
satisfaction_scores <- c(8, 7, 9, 6, 8)
urban_rural <- c("Urban", "Rural", "Urban", "Urban", "Rural")

Vector Manipulations: Retrieve items

Retrieve the first country in the vector

countries[1]
[1] "Hong Kong SAR"

Retrieves the first three satisfaction scores - use :

satisfaction_scores[1:3]
[1] 8 7 9

Retrieves the first and the third satisfaction scores - use c()

satisfaction_scores[c(1,3)]
[1] 8 9

Why square brackets and not round brackets?

Round brackets () are for running functions, like using a tool: mean() or sum().

Square brackets [] are for accessing specific parts of your data, where we pass the index number(s) of the element(s) we want.

Vector Manipulations: Retrieve items based on criteria

Let’s find high satisfaction scores (above 7)!

  • The code below will create a boolean vector called criteria that basically keep tracks on whether each items inside satisfaction_scores fulfil our condition.

  • The condition is “value must be > 7”. e.g. if item 1 fulfils our condition, then item 1 is ‘marked’ as TRUE. Otherwise, it will be FALSE

# Create boolean vector for our condition
criteria <- satisfaction_scores > 7
print(criteria)
[1]  TRUE FALSE  TRUE FALSE  TRUE
  • This line of code applies the boolean vector criteria to satisfaction_scores, and only retrieve items that fulfils the condition. i.e. only return TRUE value criteria vector
# Use the boolean vector to filter satisfaction scores
satisfaction_scores[criteria]
[1] 8 9 8

Data Structures in R: Dataframe

  • De facto data structure for tabular data in R, and what we use for data processing, plotting, and statistics.

  • Similar to spreadsheets - a rectangular collection of variables (columns) and observations (rows)!

  • You can create it by hand like so: (though more commonly you will use this to load data from external source)

survey_data <- data.frame(
    country = c("Indonesia", "Malaysia", "Turkey", "Indonesia", "Hong Kong SAR"),
    life_satisfaction = c(8, 7, 9, 6, 8),
    urban_rural = c("Urban", "Rural", "Urban", "Urban", "Rural")
)
print(survey_data)
        country life_satisfaction urban_rural
1     Indonesia                 8       Urban
2      Malaysia                 7       Rural
3        Turkey                 9       Urban
4     Indonesia                 6       Urban
5 Hong Kong SAR                 8       Rural

Downloading the World Values Survey (WVS) Dataset

For this workshop, we will try loading a dataset from a file into a dataframe!

Go to the course website and go to the ‘Dataset’ tab to download the data file and information about this synthetic WVS data

Download this CSV and save it under your data folder in your R project!

Packages in R (for additional functionalities)

  • Packages are a collections of R functions, datasets, etc. Packages extend the functionality of R.

    • (Closest analogy I can think of is that they’re equivalent of browser add-ons, in a way)
  • Popular packages: tidyverse, caret, shiny, etc.

  • Installation (you only need to do this once): install.packages("package name")

  • Loading packages (you need to run this everytime you restart RStudio): library(package name) - let’s try to load tidyverse as we will use this to load our CSV into a dataframe!

    • Tidyverse is a well-known collection of packages that facilitates data science projects. It includes packages for data manipulation, visualization, importing, and tidying.

Loading the WVS Dataset

Let’s load our actual World Values Survey dataset using read_csv function.

Before use read_csv install and load package tidyverse. Install the package only once and need to load the package in every session before you use it.

library(tidyverse)

wvs_data <- read_csv("data/wvs-4-countries.csv")
str(wvs_data)
spc_tbl_ [5,252 x 15] (S3: spec_tbl_df/tbl_df/tbl/data.frame)
 $ country               : chr [1:5252] "Hong Kong SAR" "Hong Kong SAR" "Hong Kong SAR" "Hong Kong SAR" ...
 $ respondent_id         : num [1:5252] 3.44e+08 3.44e+08 3.44e+08 3.44e+08 3.44e+08 ...
 $ age                   : num [1:5252] 28 35 52 21 30 56 46 38 25 45 ...
 $ urban_rural           : chr [1:5252] "Urban" "Urban" "Urban" "Urban" ...
 $ income_level          : chr [1:5252] "Medium" "Medium" "High" "Low" ...
 $ sex                   : chr [1:5252] "Female" "Female" "Female" "Female" ...
 $ marital_status        : chr [1:5252] "Single" "Married" "Single" "Single" ...
 $ education             : chr [1:5252] "Middle" "Higher" "Higher" "Higher" ...
 $ life_satisfaction     : num [1:5252] 8 7 9 3 8 8 6 7 7 8 ...
 $ freedom_of_choice     : num [1:5252] 8 7 8 5 8 8 6 8 7 10 ...
 $ emancipative_values   : num [1:5252] 0.633 0.452 0.512 0.631 0.377 ...
 $ trust_people          : chr [1:5252] "Trusted" "Not trusted" "Not trusted" "Not trusted" ...
 $ importance_of_god     : num [1:5252] 6 2 9 8 1 8 8 5 1 8 ...
 $ financial_satisfaction: num [1:5252] 8 5 9 3 3 8 6 1 7 8 ...
 $ secular_values        : num [1:5252] 0.405 0.474 0.554 0.128 0.384 ...
 - attr(*, "spec")=
  .. cols(
  ..   country = col_character(),
  ..   respondent_id = col_double(),
  ..   age = col_double(),
  ..   urban_rural = col_character(),
  ..   income_level = col_character(),
  ..   sex = col_character(),
  ..   marital_status = col_character(),
  ..   education = col_character(),
  ..   life_satisfaction = col_double(),
  ..   freedom_of_choice = col_double(),
  ..   emancipative_values = col_double(),
  ..   trust_people = col_character(),
  ..   importance_of_god = col_double(),
  ..   financial_satisfaction = col_double(),
  ..   secular_values = col_double()
  .. )
 - attr(*, "problems")=<pointer: 0x129ed5720> 

Make sure to save the CSV file in your data folder! (No auto save)

Exploring the WVS Dataset

We already saw str() on the previous slide. Here’s how to peek at the rows and pull out a column:

1head(wvs_data, n=5)
2wvs_data["country"]
3wvs_data$country
1
view the first 5 rows
2
retrieve column by column name (returns as tibble/dataframe)
3
another way to retrieve column by name (returns as vector). We’ll use this one a lot!

Data Structures in R: Factors

  • Special data structure in R to deal with categorical data.

  • Look (and often behave) like character vectors but are actually treated as integer vectors.

  • Can only contain a predefined set of values, known as levels. By default, R sorts levels in alphabetical order (but we can specify a custom order, as we’ll see shortly)

  • Heads-up: factor() sorts levels alphabetically, while as_factor() (which we’ll use in Session 2) keeps them in the order they first appear.

  • Can be ordered (ordinal) or unordered (nominal).

  • May look like a normal vector at first glance, so use str() to check.

  • Most common application: when we want to specify a column in our dataframe as a column of categories

Convert dataframe columns to a Factor - Unordered

In our example, country should be a factor!

str(wvs_data$country)
 chr [1:5252] "Hong Kong SAR" "Hong Kong SAR" "Hong Kong SAR" ...

Since there is no inherent order within country names, our categories will be unordered:

wvs_data$country <- factor(wvs_data$country)

# check the category levels
levels(wvs_data$country)
[1] "Hong Kong SAR" "Indonesia"     "Malaysia"      "Turkey"       

If we check the structure, country column should be a factor instead of characters now:

str(wvs_data$country)
 Factor w/ 4 levels "Hong Kong SAR",..: 1 1 1 1 1 1 1 1 1 1 ...

Convert dataframe columns to a Factor - Ordered

Some variables do have a meaningful order. For example, education has a clear progression from lower to higher. Let’s convert it to an ordered factor.

wvs_data$education <- factor(wvs_data$education,
                                levels = c("Lower", "Middle", "Higher"),
                                ordered = TRUE)

# check the category levels and structure
levels(wvs_data$education)
[1] "Lower"  "Middle" "Higher"
str(wvs_data$education)
 Ord.factor w/ 3 levels "Lower"<"Middle"<..: 2 3 3 3 2 2 3 2 3 3 ...

Trouble Shooting

Types of messages

  • Error: Fatal error in your code that prevented it from being run through successfully. Need to fix it for the code to run.

  • Warning: Non-fatal errors (don’t stop the code from running, but this is a potential problem that you should know about).

  • Message: Helpful information about the code you just ran(can usually ignore these messages)

Trouble Shooting

Check. Did you…

  • Set your working directory?

  • Check for missing commas (,), parentheses ()?

  • Check your spelling?

    • Spelling : Punctuation <- meaan(c(1, 2, 3, 4)) or print(Punctuatioon)

    • Punctuation : sum(10?20) or Punctuation <- sum(c(10, 20)))

    • Capitalization : sUm(c(5, 10, 15))

    • In text indicators : X + Y or #taking notes or “name” vs name

Recap

  • R & RStudio: R is a programming language for statistical computing and graphics, while RStudio is an environment that makes it easier to write, run, and manage R code.

  • Working Directory: A folder on your computer where R reads and saves files.

  • Data Type: Types of value an object can hold, such as numeric, character, and Boolean.

  • Data Structure: Data structures organize and store data in R, such as vectors, factors, and data frames.

  • Functions: Reusable codes that perform specific tasks. Can call functions with arguments.

  • Packages: Collections of functions and data to perform tasks. Need to install and load packages.

Coming up next: why do we need to clean our data?

Converting country and education into factors was our first taste of data cleaning: making the data reflect what it actually means. Next session is all about this, so here’s why it matters:

  • Researchers spend 60-80% of their time on data preparation - investing in proper wrangling upfront saves hours of debugging and rework later.
  • Poor data quality costs projects or organizations millions annually(!), and even one misclassified data point can skew entire analyses.
  • Clean data improves the workflow for statistical tests and can reveal hidden patterns that aren’t visible in messy datasets
  • Well-documented data cleaning makes research transparent and reproducible, benefiting both future-you and collaborators.

Why do it in R? Can’t I do this on excel?

  • Reproducible record: your script shows exactly what you did; Excel clicks are hard to track
  • No silent auto-“corrections”: Excel can quietly change your data (like flipping dates from DDMMYY to MMDDYY)
  • Rerun on new data: write the cleaning code once, apply it again when the data updates

End of Session 1!

Remember our goal: enough fundamentals that ChatGPT can’t bluff you so easily. You can now read R code that creates objects, calls functions, and works with vectors, dataframes and factors.

Next Session: Data wrangling with dplyr and tidyr packages - we’ll learn how to:

  • Filter survey responses by country

  • Calculate average satisfaction scores by demographic groups

  • Create new variables from existing ones

  • Handle missing values in survey data

  • And much more!

Quiz Time! (compulsory)

Scan the QR Code below to assess your understanding of the basics of R and RStudio, including their purpose, key concepts, and fundamental commands. All questions are required and each is worth 1 mark.

Quiz QR Code: https://forms.cloud.microsoft/r/pvCRpgbQeT

Quiz QR Code: <https://forms.cloud.microsoft/r/pvCRpgbQeT>

Appendix on Vector Manipulations: Add items

Several ways to add items to a vector

1satisfaction_scores <- c(satisfaction_scores, 7)
2satisfaction_scores <- c(satisfaction_scores, 8, 9, 10)
3satisfaction_scores <- c(8, satisfaction_scores)
4satisfaction_scores <- append(satisfaction_scores, 9, after = 2)
1
Add a single score to the end of the vector using c()
2
Add multiple scores to the end
3
Add a score to the beginning
4
Insert a score at a specific position using append(vector_name, elements_to_be_added, from_the_position)

Appendix on Vector Manipulations: Handle NA values

  • NA values indicate null values, or the absence of a value (0 is still a value!)

  • Summary functions like mean needs you to include argument called na.rm on how you want it to be handled.

Survey data often contains missing values (NA):

financial_satisfaction <- c(8, 7, NA, 6, 9, NA, 7)

# By default, mean() will return NA if there are any NA values
mean(financial_satisfaction)
[1] NA
# Remove NA values before calculating mean by including na.rm = TRUE
mean(financial_satisfaction, na.rm = TRUE)
[1] 7.4

Appendix on Vector Manipulations: Edit item

Update the first satisfaction score

satisfaction_scores[1] <- 7
print(satisfaction_scores)
[1] 7 7 9 6 8

Appendix on Vector Manipulations: Remove items

1satisfaction_scores <- satisfaction_scores[-c(2, 4)]
2satisfaction_scores <- satisfaction_scores[satisfaction_scores <= 7]
3satisfaction_scores <- na.omit(satisfaction_scores)
1
Remove elements by index using “negative indexing”
2
Remove elements based on a condition using logical indexing. Remove these items which are FALSE.
3
Remove NA values from the vector

Appendix on Dataframes: More ways to explore

1dim(wvs_data)
2names(wvs_data)
3str(wvs_data)
4summary(wvs_data)
5head(wvs_data, n=5)
6tail(wvs_data, n=5)
1
return a vector of number of rows and columns
2
inspect columns
3
inspect structure
4
print the summary stats of the entire dataframe
5
view the first 5 rows
6
view the last 5 rows

Appendix on Dataframes: More ways to retrieve values

1wvs_data["country"]
2wvs_data$country
3wvs_data[3]
4wvs_data[1, 4]
5wvs_data[3, ]
1
retrieve column by column name (returns as tibble/dataframe)
2
another way to retrieve column by name (returns as vector)
3
retrieve column by index
4
get a cell at this row, column coord
5
get an entire row