Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

factor
r
function
communitycreator

How to create a factor in R?

Onyejiaku Theophilus Chidalu

Overview

A factor in R is used to categorize data. For example:

  • Temperature: Cold/Hot
  • Sex: Male/Female
  • Height: Tall/Average/Short

The above are simple examples of factors.

Creating a factor in R

To create a factor in R, we make use of the factor() function.

Syntax

factor(level(s))

Parameter value

The factor() function takes the level(s) corresponding to the factor variable as its parameters.

Return value

The factor() function returns an object class factor.

Code example

# creating a factor 
Height <- factor(c("Tall", "Average", "Short"))

# printing the factor
Height
Implementing the factor() function

Code explanation

  • Line 2: We create a factor variable Height using the factor() function.
  • Line 5: We print the factor object Height.

Printing only the levels of the factor

To print only the levels corresponding to a factor variable, we use the levels() function.

Syntax

levels(factor)

Parameter value

The levels() function takes the factor variable as its single parameter value.

Code example

# creating a factor 
Height <- factor(c("Tall", "Average", "Short", "Average", "Short"))
# printing the levels
levels(Height)
Implementing the levels function

RELATED TAGS

factor
r
function
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring