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 characterH
as index1
, the second charactere
has index position or number as2
, and so on.
# 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]
Names
having 4 items.1
) of the factor object Names
.2
) of the factor object Names
.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
# creating a factorNames <- factor(c("Theophilus", "Chidalu", "David", "Joseph"))# using a for loopfor (index in 1:length(Names)){print(Names[index])}
Line 2: We create a factor object Names
having 4 items.
Line 5: Using a for
loop, we call the variable index
to represents all the index position of all the items of the factor by using the length()
function.
Line 6: We print the variable index
which represents all the items of the factor Names
.
# creating a factorNames <- factor(c("Theophilus", "Chidalu", "David", "Joseph"))# using a for loopfor (Name in Names){print(Name)}
Line 2: We create a factor object Names
having 4 items.
Line 5: Using a for
loop, we use the variable Name
to select of all the items one by one of the factor Names
.
Line 6: We print the variable Name
which represents all the items of the factor Names
.