How to access the items of a factor in R
Overview
A factor in R is used to categorize data. The corresponding values in a factor are referred to as the items of the factor.
To access these factor items, we refer to their respective index number or position in the factor using square brackets [].
It is worth noting that the first character of an object in R has an index position of
1. For example, the string"Hello"has its first characterHas index1, the second characterehas index position or number as2, and so on.
Code
# creating a factorNames <- factor(c("Theophilus", "Chidalu", "David", "Joseph"))# printing the first item(index 1) of the factorNames[1]# priting the second item of the factorNames[2]
Explanation
- Line 2: We create a factor object
Nameshaving 4 items. - Line 5: We access and print the first item (index
1) of the factor objectNames. - Line 8: We access and print the second item (index
2) of the factor objectNames.
It is worth noting that the output
(Levels: Chidalu David Joseph Theophilus)which comes after the accessed item(s) of the list represents the levels of the factor.
Interestingly we can use a for loop to also access the items of a factor
Code
# creating a factorNames <- factor(c("Theophilus", "Chidalu", "David", "Joseph"))# using a for loopfor (index in 1:length(Names)){print(Names[index])}
Explanation
-
Line 2: We create a factor object
Nameshaving 4 items. -
Line 5: Using a
forloop, we call the variableindexto represents all the index position of all the items of the factor by using thelength()function. -
Line 6: We print the variable
indexwhich represents all the items of the factorNames.
Code
# creating a factorNames <- factor(c("Theophilus", "Chidalu", "David", "Joseph"))# using a for loopfor (Name in Names){print(Name)}
Explanation
-
Line 2: We create a factor object
Nameshaving 4 items. -
Line 5: Using a
forloop, we use the variableNameto select of all the items one by one of the factorNames. -
Line 6: We print the variable
Namewhich represents all the items of the factorNames.