COSMOS logo

Data in R

Zhaoxia Yu

Data

  • Data are raw facts or measurements that can be processed and analyzed to produce information and support decision-making.
Data Information
Raw facts, observations, or measurements Patterns, relationships, or conclusions derived from data
May be unorganized or unprocessed Organized and useful for decision-making
Example: Blood pressure measurements of patients Example: “The average blood pressure is higher in the treatment group than in the control group.”
  • Data become information through analysis, interpretation, and visualization. This transformation is a central goal of data science.

Data in R

  • How does R handle data? R has several built-in data structures to store and manipulate data, such as:
    • Vectors: One-dimensional arrays that can hold numeric, character, or logical data.
    • Matrices: Two-dimensional arrays with rows and columns, where all elements are of the same type.
    • Data frames: Two-dimensional tables that can hold different types of data in each column.
    • Lists: Collections of objects that can contain different types of data.

Getting Data into R

Method Typical Sources Examples
Create data in R Small examples, simulations c(), matrix(), data.frame()
Import local files Data stored on your computer CSV, Excel, TXT, MAT, SAS, SPSS
Load built-in datasets Datasets included with R or R packages data(iris), data(mtcars)
Import online data Files hosted online Read from a URL
Access data through APIs Databases and web services World Bank, Census Bureau

Create Data

Create Variables and Data Frames

  • Create Variables
Code
age  <- c(45, 61, 53, 38)
sex  <- c("F", "M", "F", "M")
bmi  <- c(23.4, 28.7, 25.1, 21.8)
  • Create A Data Frame
Code
patients <- data.frame(
  Age = age,
  Sex = sex,
  BMI = bmi
)

patients
  Age Sex  BMI
1  45   F 23.4
2  61   M 28.7
3  53   F 25.1
4  38   M 21.8

Create A List

Code
study <- list(
  data = patients,
  investigator = "Dr. Smith",
  sample_size = nrow(patients)
)

study
$data
  Age Sex  BMI
1  45   F 23.4
2  61   M 28.7
3  53   F 25.1
4  38   M 21.8

$investigator
[1] "Dr. Smith"

$sample_size
[1] 4

Create A Matrix

Code
# Matrix: all values must have the same type
m <- matrix(1:6, nrow = 2)
m
     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6

Tip

Key Ideas

  • A variable stores a value or a collection of values.
  • A data frame stores tabular data, where each column is a variable and different columns can have different data types.
  • A matrix stores data in rows and columns; all elements having the same data type.
  • A list can store objects of different types, including vectors, matrices, data frames, and even other lists.

Create Data by Simulating Random Numbers

set.seed(123)     # Make results reproducible

sim_data <- data.frame(
  ID = 1:100,
  Age = round(rnorm(100, mean = 50, sd = 12)),
  BMI = round(rnorm(100, mean = 26, sd = 4), 1),
  Treatment = sample(c("Control", "Drug"),
                     100, replace = TRUE)
)

Note

Why simulate data?

Simulated data allow us to test code, evaluate statistical methods, and practice data analysis when real data are unavailable or contain sensitive information.

Import Data from Local

alzheimer_data <- read.csv('data/alzheimer_data.csv')

Tips

  • Specify the correct file path. The path should point to the location of the file relative to your current working directory.
  • Use the appropriate import function. For CSV files, use read.csv() (base R) or readr::read_csv() (tidyverse).
  • Check your working directory. Use getwd() to see the current working directory and list.files() to verify that the file is there.
  • Assign the imported data to a variable so you can use it later in your analysis.
  • Inspect the imported data using functions such as head(), str(), summary(), or View() to ensure it was imported correctly.

Built-in Data

Built-in Datasets

R includes many built-in datasets. Examples:

Dataset Description
iris Measurements of iris flowers
mtcars Motor vehicle performance
airquality Daily air quality measurements in New York
ToothGrowth Tooth growth in guinea pigs
Titanic Survival counts from the Titanic disaster

Tip

Built-in datasets are convenient because they require no downloading or importing and are available immediately after installing R.

Load a Built-in Dataset

Use the data() function to load a built-in dataset.

Code
# Load the iris dataset
data(iris)

# Display the first six rows
head(iris)
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

To obtain help for a dataset:

Code
?iris

Explore a Built-in Dataset

Note

A good habit is to inspect every dataset after loading it to understand its variables, data types, and dimensions before performing any analysis.

Code
dim(iris)        # Number of rows and columns
[1] 150   5
Code
names(iris)      # Variable names
[1] "Sepal.Length" "Sepal.Width"  "Petal.Length" "Petal.Width"  "Species"     
Code
str(iris)        # Structure of the dataset
'data.frame':   150 obs. of  5 variables:
 $ Sepal.Length: num  5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
 $ Sepal.Width : num  3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
 $ Petal.Length: num  1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
 $ Petal.Width : num  0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
 $ Species     : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
Code
summary(iris)    # Summary statistics
  Sepal.Length    Sepal.Width     Petal.Length    Petal.Width   
 Min.   :4.300   Min.   :2.000   Min.   :1.000   Min.   :0.100  
 1st Qu.:5.100   1st Qu.:2.800   1st Qu.:1.600   1st Qu.:0.300  
 Median :5.800   Median :3.000   Median :4.350   Median :1.300  
 Mean   :5.843   Mean   :3.057   Mean   :3.758   Mean   :1.199  
 3rd Qu.:6.400   3rd Qu.:3.300   3rd Qu.:5.100   3rd Qu.:1.800  
 Max.   :7.900   Max.   :4.400   Max.   :6.900   Max.   :2.500  
       Species  
 setosa    :50  
 versicolor:50  
 virginica :50  
                
                
                
Code
head(iris)       # First six rows
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa
3          4.7         3.2          1.3         0.2  setosa
4          4.6         3.1          1.5         0.2  setosa
5          5.0         3.6          1.4         0.2  setosa
6          5.4         3.9          1.7         0.4  setosa

All Available Built-in Datasets

To see all available built-in datasets:

Code
data()

URL

Import Data from a URL

Ex1=read.csv("https://www.ics.uci.edu/~zhaoxia/Data/BeyondTandANOVA/Example1.txt", head=T)
alzheimer_data <- read.csv("https://raw.githubusercontent.com/COSMOS-DataScience/slides/refs/heads/main/data/alzheimer_data.csv", head=T)

API

Import Data Through an API

An API (Application Programming Interface) allows R to request data directly from an online database or web service.

  • Retrieve data directly from the source without manually downloading files.
  • Request only the data you need (e.g., specific countries, years, or variables).
  • Access the latest available data whenever the code is run.
  • Improve reproducibility by using the same code to retrieve updated data.

API

Note

An API is a communication interface, not a data source.

The API connects your R program to an online database.

The timeliness of the data depends on how frequently the database is updated.

Example: Import Data from the World Bank API

The WDI package provides an R interface to the World Bank API.

Tip

The WDI() function sends a request to the World Bank API, retrieves the requested data, and returns them as a data frame for analysis in R.

Code
# I changed it to eval:false because API cannot be connected on 07/10/2026 at around 9:30pm PCT. Will check later

# I changed it to eval:false because API con
if (!requireNamespace("WDI", quietly = TRUE)) {
  install.packages("WDI")
}

library(WDI)

gdp <- WDI(
  country = c("US", "CN", "JP"),
  indicator = "NY.GDP.PCAP.CD",
  start = 2020,
  end = 2024
)

head(gdp)

Example: Retrieve Weather Data

The Open-Meteo API provides current weather observations and hourly forecasts. Workflow:

  1. Construct a URL specifying the location and weather variables.
  2. Send the request to the Open-Meteo API.
  3. Receive the data in JSON format.
  4. Use jsonlite::fromJSON() to convert the JSON response into R objects.
  5. Analyze the returned data just like any other dataset.

Tip

Unlike the World Bank API, which provides periodically updated statistics, the Open-Meteo API provides current conditions and hourly forecasts.

Note

Variable names

  • temperature_2m: Air temperature measured 2 meters above the ground.
  • relative_humidity_2m: Relative humidity measured 2 meters above the ground.
  • wind_speed_10m: Wind speed measured 10 meters above the ground.
# Install jsonlite if necessary
if (!requireNamespace("jsonlite", quietly = TRUE)) {
  install.packages("jsonlite")}

library(jsonlite)

url <- paste0(
  "https://api.open-meteo.com/v1/forecast?",
  "latitude=33.6405&longitude=-117.8443",
  "&current=temperature_2m,relative_humidity_2m,wind_speed_10m",
  "&hourly=temperature_2m"
)

weather <- fromJSON(url)

Current Weather

Code
weather$current
$time
[1] "2026-07-11T04:15"

$interval
[1] 900

$temperature_2m
[1] 18

$relative_humidity_2m
[1] 90

$wind_speed_10m
[1] 6.4

Hourly Forecast

Code
head(weather$hourly, 2)
$time
  [1] "2026-07-11T00:00" "2026-07-11T01:00" "2026-07-11T02:00"
  [4] "2026-07-11T03:00" "2026-07-11T04:00" "2026-07-11T05:00"
  [7] "2026-07-11T06:00" "2026-07-11T07:00" "2026-07-11T08:00"
 [10] "2026-07-11T09:00" "2026-07-11T10:00" "2026-07-11T11:00"
 [13] "2026-07-11T12:00" "2026-07-11T13:00" "2026-07-11T14:00"
 [16] "2026-07-11T15:00" "2026-07-11T16:00" "2026-07-11T17:00"
 [19] "2026-07-11T18:00" "2026-07-11T19:00" "2026-07-11T20:00"
 [22] "2026-07-11T21:00" "2026-07-11T22:00" "2026-07-11T23:00"
 [25] "2026-07-12T00:00" "2026-07-12T01:00" "2026-07-12T02:00"
 [28] "2026-07-12T03:00" "2026-07-12T04:00" "2026-07-12T05:00"
 [31] "2026-07-12T06:00" "2026-07-12T07:00" "2026-07-12T08:00"
 [34] "2026-07-12T09:00" "2026-07-12T10:00" "2026-07-12T11:00"
 [37] "2026-07-12T12:00" "2026-07-12T13:00" "2026-07-12T14:00"
 [40] "2026-07-12T15:00" "2026-07-12T16:00" "2026-07-12T17:00"
 [43] "2026-07-12T18:00" "2026-07-12T19:00" "2026-07-12T20:00"
 [46] "2026-07-12T21:00" "2026-07-12T22:00" "2026-07-12T23:00"
 [49] "2026-07-13T00:00" "2026-07-13T01:00" "2026-07-13T02:00"
 [52] "2026-07-13T03:00" "2026-07-13T04:00" "2026-07-13T05:00"
 [55] "2026-07-13T06:00" "2026-07-13T07:00" "2026-07-13T08:00"
 [58] "2026-07-13T09:00" "2026-07-13T10:00" "2026-07-13T11:00"
 [61] "2026-07-13T12:00" "2026-07-13T13:00" "2026-07-13T14:00"
 [64] "2026-07-13T15:00" "2026-07-13T16:00" "2026-07-13T17:00"
 [67] "2026-07-13T18:00" "2026-07-13T19:00" "2026-07-13T20:00"
 [70] "2026-07-13T21:00" "2026-07-13T22:00" "2026-07-13T23:00"
 [73] "2026-07-14T00:00" "2026-07-14T01:00" "2026-07-14T02:00"
 [76] "2026-07-14T03:00" "2026-07-14T04:00" "2026-07-14T05:00"
 [79] "2026-07-14T06:00" "2026-07-14T07:00" "2026-07-14T08:00"
 [82] "2026-07-14T09:00" "2026-07-14T10:00" "2026-07-14T11:00"
 [85] "2026-07-14T12:00" "2026-07-14T13:00" "2026-07-14T14:00"
 [88] "2026-07-14T15:00" "2026-07-14T16:00" "2026-07-14T17:00"
 [91] "2026-07-14T18:00" "2026-07-14T19:00" "2026-07-14T20:00"
 [94] "2026-07-14T21:00" "2026-07-14T22:00" "2026-07-14T23:00"
 [97] "2026-07-15T00:00" "2026-07-15T01:00" "2026-07-15T02:00"
[100] "2026-07-15T03:00" "2026-07-15T04:00" "2026-07-15T05:00"
[103] "2026-07-15T06:00" "2026-07-15T07:00" "2026-07-15T08:00"
[106] "2026-07-15T09:00" "2026-07-15T10:00" "2026-07-15T11:00"
[109] "2026-07-15T12:00" "2026-07-15T13:00" "2026-07-15T14:00"
[112] "2026-07-15T15:00" "2026-07-15T16:00" "2026-07-15T17:00"
[115] "2026-07-15T18:00" "2026-07-15T19:00" "2026-07-15T20:00"
[118] "2026-07-15T21:00" "2026-07-15T22:00" "2026-07-15T23:00"
[121] "2026-07-16T00:00" "2026-07-16T01:00" "2026-07-16T02:00"
[124] "2026-07-16T03:00" "2026-07-16T04:00" "2026-07-16T05:00"
[127] "2026-07-16T06:00" "2026-07-16T07:00" "2026-07-16T08:00"
[130] "2026-07-16T09:00" "2026-07-16T10:00" "2026-07-16T11:00"
[133] "2026-07-16T12:00" "2026-07-16T13:00" "2026-07-16T14:00"
[136] "2026-07-16T15:00" "2026-07-16T16:00" "2026-07-16T17:00"
[139] "2026-07-16T18:00" "2026-07-16T19:00" "2026-07-16T20:00"
[142] "2026-07-16T21:00" "2026-07-16T22:00" "2026-07-16T23:00"
[145] "2026-07-17T00:00" "2026-07-17T01:00" "2026-07-17T02:00"
[148] "2026-07-17T03:00" "2026-07-17T04:00" "2026-07-17T05:00"
[151] "2026-07-17T06:00" "2026-07-17T07:00" "2026-07-17T08:00"
[154] "2026-07-17T09:00" "2026-07-17T10:00" "2026-07-17T11:00"
[157] "2026-07-17T12:00" "2026-07-17T13:00" "2026-07-17T14:00"
[160] "2026-07-17T15:00" "2026-07-17T16:00" "2026-07-17T17:00"
[163] "2026-07-17T18:00" "2026-07-17T19:00" "2026-07-17T20:00"
[166] "2026-07-17T21:00" "2026-07-17T22:00" "2026-07-17T23:00"

$temperature_2m
  [1] 21.8 21.7 20.8 19.1 18.2 17.5 17.1 17.7 17.2 17.7 17.5 17.4 17.5 17.5 17.9
 [16] 19.5 19.1 19.4 22.5 23.2 23.0 23.1 22.5 22.8 22.1 21.7 20.4 19.4 18.6 18.6
 [31] 18.5 18.0 18.0 17.9 17.2 17.7 17.8 17.4 18.1 18.7 20.4 22.1 21.1 22.8 22.0
 [46] 22.4 23.2 24.5 24.6 24.9 23.8 23.5 22.8 22.3 22.0 21.7 21.6 21.7 21.8 21.8
 [61] 21.7 21.4 21.9 22.9 24.4 25.6 27.1 25.8 26.6 28.5 29.9 29.5 27.7 26.1 24.9
 [76] 24.0 23.3 23.1 22.8 22.7 22.7 22.4 21.9 21.8 21.6 21.6 22.0 23.4 25.6 27.6
 [91] 29.2 29.9 30.3 30.0 29.9 29.6 29.0 28.5 27.0 25.3 24.3 24.0 24.0 23.7 23.2
[106] 23.0 22.6 22.4 22.2 22.1 22.7 24.1 25.8 27.5 29.2 30.4 31.4 31.9 31.9 31.5
[121] 30.7 29.2 27.3 25.8 24.8 24.2 23.7 23.1 22.7 22.3 21.9 21.7 21.7 21.9 22.5
[136] 23.2 24.3 25.6 26.6 27.1 27.4 27.4 27.1 26.5 25.8 24.8 23.8 22.9 22.3 21.9
[151] 21.7 21.5 21.4 21.4 21.2 21.0 21.1 21.3 21.8 22.6 24.0 25.7 27.1 27.8 28.1
[166] 28.1 27.7 27.0

The first row of weather$hourly is the first available forecast time, followed by the next forecast hour.

A Fun Example: Exploring Datasets with tidytuesdayR

Example: Load Weekly Datasets with tidytuesdayR

if (!requireNamespace("tidytuesdayR", quietly = TRUE)) {
  install.packages("tidytuesdayR")
}

library(tidytuesdayR)

# Download one week's datasets
tt <- tt_load("2026-06-30")

# Show available datasets
tt

# View the README
readme(tt)
Code
# Load one dataset
names(tt)
[1] "wreck_inventory"
Code
head(tt[[1]])
# A tibble: 6 × 11
  date        year wreck_name         wreck_no classification description       
  <date>     <dbl> <chr>              <chr>    <chr>          <chr>             
1 1894-12-28  1894 Actur              W00001   Schooner       "Schooner of Dubl…
2 1862-01-22  1862 Anne McLeod        W00007   Schooner       "71-ton, 6-year-o…
3 1824-02-18  1824 Barbara & Jannette W00008   Sloop          "Sloop en route f…
4 1888-10-19  1888 Bee (SS)           W00009   Iron Steamship "88-ton, 18-year-…
5 1838-10-23  1838 Bloom              W00010   Schooner       "Schooner valued …
6 1886-07-31  1886 Breadalbane        W00011   Brig           "115-ton, 23-year…
# ℹ 5 more variables: descriptive_date <chr>, place_of_loss <chr>,
#   latitude <dbl>, longitude <dbl>, source_of_co_ordinate <chr>

About TidyTuesday

Each TidyTuesday release includes:

  • One or more datasets
  • A README describing the data and variables
  • Links to the original data source
  • Ideas for data visualization and analysis