Data Structures
Overview
Teaching: 20 min
Exercises: 0 minQuestions
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:
- characters a, b
- numeric: 2.3
- interger: 5 or 5L
- complex: 2+3i #consists of real and imaginary number
- logical: TRUE/FALSE
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
- In R, the number is considered as numeric
e <- 5 class(e) - To get an integer, insert
Las suffixf <- 5L class(f) - Special number:
Inf: infinityg<-5/0 class(g) NaN(Not a Number) orNA(Not Applicable) are undefined values and sometimes refered as missing values:h <- 0/0 i <- NA h i
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:
- is.na() test NA value
- is.nan() test NaN value
- is.infinite() test Inf value
- NaN is NA but the reverse is false
v <- c(TRUE, 6, 1/0,NA, NaN,-6/0) v is.na(v) is.nan(v) is.infinite(v)
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