Types of Objects in R
There are majorly 5 types of objects in R:
In R variables can be initialized using ' <- ' or ' = ' o ' -> ' operators. There are 4 types of variables in R : numeric, character, factors and Boolean.
Numeric variables contain float and integer values.
x = 5 x <- 5 5 -> x #Less used way x = 5L #Treats as an integer
You can print the values of the variable by:
x print(x) #Alternatively
Character variables are strings: Please remember that R is case sensitive - thus it treats X and x as two different variables
x = "You are awesome!" X = "You are awesome"
Factors are string variables but are ordinal in nature.
a = factor(c("low","high","high","low","medium"))
Boolean or Logical: Contains TRUE and FALSE values.
2 > 3 X = 5; X < 10
Collection of elements of same type is a vector.
X = c(1234,5678) X = 1:10 # Defining a sequence of numbers from 1 to 10 X = seq(from = 1,to = 10,by= 2) X = c(T,F,F,T) # A logical vector X = c(1+6i, 9+0i) # A vector of complex numbers
You can check the class of vector by using class function:
Length of a vector can be determined by using length function:
Matrices in R are 2D arrays where each element have same class:
dim() function provides the dimensions of a matrix; First number depicts the number of rows and the other denotes the number of columns.
You do not need to provide all the dimensions of a matrix. For example in the code below, R can itself understand that number of columns would be 3.
my_matrix = matrix(1:9,nrow = 3)
Note: by default R enters the data column wise, if you want the data to be entered row-wise thus you need to define byrow = T You can also change the row and column names for a matrix by using rownames and colnames functions.
Data Frame is a 2D away where each column has elements of same time, but two different columns can have two different data types. For instance. One column can contain the Patient Name and other column can contain their Blood Pressures.
In the following data frame we are creating 3 columns: Name of the avenger, their weights (in kgs) and whether a person likes them or not:
Lists can contain elements of various objects, they need not be of same class. Following list contains 3 different information: a counting, students name (2 students only) and marks of 4 students.
Note: A data frame can always be transformed to a list, but the converse is not always feasible.
To learn about how to subset (filter) these various R objects, you can refer to the tutorial: Filtering different objects in R