Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

r
communitycreator

# How to access the items of a factor in R

Onyejiaku Theophilus Chidalu

### 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 character H as index 1, the second character e has index position or number as 2, and so on.

### Code

# creating a factor
Names <- factor(c("Theophilus", "Chidalu", "David", "Joseph"))

# printing the first item(index 1) of the factor
Names[1]

# priting the second item of the factor
Names[2]
Accessing the items of a factor

### Explanation

• Line 2: We create a factor object Names having 4 items.
• Line 5: We access and print the first item (index 1) of the factor object Names.
• Line 8: We access and print the second item (index 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

### Code

# creating a factor
Names <- factor(c("Theophilus", "Chidalu", "David", "Joseph"))

# using a for loop
for (index in 1:length(Names)){
print(Names[index])
}
Using a for loop

### Explanation

• 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.

### Code

# creating a factor
Names <- factor(c("Theophilus", "Chidalu", "David", "Joseph"))

# using a for loop
for (Name in Names){
print(Name)
}


Using a for loop to access the item of a factor

### Explanation

• 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.

RELATED TAGS

r
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring

Learn in-demand tech skills in half the time