1. Introduction to R

Author

G.H. Koo

In this first tutorial, we begin with the core building blocks of R. We will explore data structures in more detail in Chapter 2.

# --------------------------------------------------
# Creating objects and basic arithmetic
# --------------------------------------------------

# Store values using the assignment operator <-
x <- 10
y <- 5

# Perform basic calculations
x + y
[1] 15
x * y
[1] 50
# --------------------------------------------------
# Creating and exploring a data frame
# --------------------------------------------------

# Create a simple data frame of cities
cities <- data.frame(
  name = c("Washington DC", "Paris", "Seoul"),
  population = c(693645, 2048472, 9600000)
)

# View the data frame
cities
           name population
1 Washington DC     693645
2         Paris    2048472
3         Seoul    9600000
# Check column names
colnames(cities)
[1] "name"       "population"
# --------------------------------------------------
# Accessing data
# --------------------------------------------------

# Access a column using $
cities$population
[1]  693645 2048472 9600000
# Access rows and columns using indexing [row, column]
cities[1, ]          # First row
           name population
1 Washington DC     693645
cities[, "name"]     # Name column
[1] "Washington DC" "Paris"         "Seoul"        
# --------------------------------------------------
# Using functions
# --------------------------------------------------

# Calculate summary statistics
mean(cities$population)
[1] 4114039
sd(cities$population)
[1] 4799033
# --------------------------------------------------
# Creating new variables
# --------------------------------------------------

# Add a new column
cities$double_population <- cities$population * 2

# View updated data frame
cities
           name population double_population
1 Washington DC     693645           1387290
2         Paris    2048472           4096944
3         Seoul    9600000          19200000

Your first code example

As a warm-up, we begin with a cowsay package to run our initial codes.

Note

The cowsay package displays messages using ASCII art animals. This makes console output more fun and engaging.

Install the package from CRAN onto your computer and load the package (once you install a package, you do not need to re-install it again. Next time, just use library() without install.packages().

#install.packages("cowsay")  
library(cowsay)
say("Hello world!")

 -------------- 
< Hello world! >
 -------------- 
      \
       \

        ^__^ 
        (oo)\ ________ 
        (__)\         )\ /\ 
             ||------w|
             ||      ||
say("I'm EGGS-hausted!.\n - Fluffy chicken",
    by = "chicken")

 -------------------------------------- 
< I'm EGGS-hausted!.  - Fluffy chicken >
 -------------------------------------- 
      \
       \
         _
       _/ }
      `>' \
      `|   \
       |   /'-.     .-.
        \'     ';`--' .'
         \'.    `'-./
          '.`-..-;`
            `;-..'
            _| _|
            /` /` [nosig]
 
Tip

Tip: If you type ? followed by a function name, the Help window will open on the right and explain what the function does

?say
Note

Try different animals! If you enter an animal name that is not supported, R will return an error such as: Error: unknown animal. The message will also display a list of supported animals; for example frog, ghost, pumpkin, dragon, bat, owl, duck, yoda, alligator.

say("catfact", "cat")

 ------------------------------------------------------ 
/ Cats often overract to unexpected stimuli because of \
\ their extremely sensitive nervous system.            /
 ------------------------------------------------------ 
         \
          \

            |\___/|
          ==) ^Y^ (==
            \  ^  /
             )=*=(
            /     \
            |     |
           /| | | |\
           \| | |_|/\
      jgs  //_// ___/
               \_)
  
say("It is going to snow this weekend. Stay warm! 
    — Dr. Koo", "snowman")

 --------------------------------------------------------- 
<It is going to snow this weekend. Stay warm!  — Dr. Koo>
 --------------------------------------------------------- 
  \
   \

     _[_]_
      (")
  >--( : )--<
    (__:__) [nosig]
  

Practice: Years Since Major Historical Events

Tip

Task

  1. Calculate how many years have passed since: the first computer (1946) + the first moon landing (1969).

  2. Print each result and the total number of years.

first_computer <- 1946
first_moon_landing <- 1969
current_year <- 2026 #ENTER THE CURRENT YEAR

Calculate years since events

years_since_computer <- current_year - first_computer
print(years_since_computer)
[1] 80
years_since_moon <- current_year - first_moon_landing
print(years_since_moon)
[1] 57

Sum of years since events

total_years <- years_since_computer + years_since_moon
print(total_years)
[1] 137
Note

Tip: Remember to label your R code chunks

When writing code in your R Markdown, make sure that every R code block starts with three backticks and {r}, and also ends with three backticks. The backtick key is usually located next to the 1 key on your keyboard (the same key as ~).