Classes of Objects
Intro to Object Classes
All data and objects in R fall into a class. Classes describe the object and tell R how to interpret the information.
Most often, you will work with objects from the classes: character, numeric, and logical
However, be aware that many custom classes exist for different types of data!
You can find the class of an object by using the function class()
class(2) #numeric
class('Urban') #character
class(1==2) #logical
## [1] "numeric"
## [1] "character"
## [1] "logical"
In the below example, we assign numeric data to the variable x. This gives x the class numeric.
x <- 2+4
class(x)
## [1] "numeric"
Character
Character objects are composed of letters, numbers, and symbols, often referred to as strings. Common strings include dates, names, and locations. You cannot perform mathematical operations over a character object. We can specify an object as a character by using quotation marks (double or single!).
x <- "string double quotes"
x
class(x)
x <- 'string single quotes'
x
class(x)
## [1] "string double quotes"
## [1] "character"
## [1] "string single quotes"
## [1] "character"
The next example shows what would happen if you tried to add the number 3 to a character object. Even though the character is the number 3, we cannot apply mathematical operations over it because it is in the character class. To r, this would be like trying to add 2 to the word apple.
x <- "3"
x
class(x)
x + 2
## Error in x + 2: non-numeric argument to binary operator
## [1] "3"
## [1] "character"
Numeric
Numeric objects are simply numbers. A numeric refers to any number whether they be whole numbers (integers) or if they contain decimals (doubles). Numeric objects can have mathematical operations performed on them.
x <- 2
class(x)
x <- 2.5
class(x)
x + 2
class(x+2)
## [1] "numeric"
## [1] "numeric"
## [1] 4.5
## [1] "numeric"
Logical
Logical objects need to be either TRUE or FALSE values. These are often used for presence/absence, TRUE/FALSE, or any other type of binary data. Additionally, logical objects can be used to compare one value to another value. These are really useful while cleaning your data.
class(TRUE)
class(FALSE)
## [1] "logical"
## [1] "logical"
We can create logic by comparing 2 values with the double equal sign
1==1
1==2
## [1] TRUE
## [1] FALSE
Doing so results in a logical object as we save the output
x <- 1==2
class(x)
x
## [1] "logical"
## [1] FALSE
There are many more data classes that you can work with, but this lesson provides the most common classes you will find on your R journey!