This lesson is being piloted (Beta version)

Data Structures

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • Class of objects in R?

  • Data Type in R?

  • How many type of number in R?

  • Missing values

  • Subsetting

Objectives
  • Identify 5 class of objects

  • Working with List

  • Type of number in R

  • Replace number with subset

Classes of objects

In R, there are 5 main classes of objects:

str <- "string"
class(str)
a <- 5
class(a)
b <- 4L
class(b)
c <- 6i ^ (-3:3)
class(c)
d <- 1:10 < 5
class(d)

List

A vector that containts objects from different class is call a list

list1 <- list(str,a,b,c,d)
list1

Number

Random Number & seed

Create random numeric numbers using runif

runif(1)
runif(3)
runif(2,10,20)

Create random integer numbers using sample

sample(12,5)
sample(12)
sample(letters,4)

Introduction to seed

Set the seed of R’s random number generator, which is useful for creating simulations or random objects that can be reproduced.

set.seed(1234)
runif(3)

Missing values

In order to test the missing values or bad values NaN, NA, Inf use some math operations:

Subsetting

In order to extract the necessary information, subsetting is used. In R, subsetting is represented by bracket: []

str <- c("a", "b","c","d")
str
# Find the subset with index 1 for str:
str[1]
# Find the subset with index 2:4 for str:
str[2:4]

Subsetting with List

list1 <- list(l1=str,l2=4:6)
list1
# Use $ to call a variable name
list1$l1[3]

Subsetting matrix

m <- matrix(1:12,nrow=3,ncol=4)
m
m[2,3]

Subsetting by row or column:

m[2,]
m[,4]

Subsetting NA/NaN value

a <- c(1:5,NaN,TRUE)
a
# Find the location of *NaN* value using `is.nan()` function
ind <- is.nan(a)
ind
# Subset with location of *NaN* value
a[ind]
a[is.nan(a)]
# Subset with location of `Not NaN` values using `!`
a[!ind]

Key Points

  • Class of objects

  • Subsetting