What is a factor in R, and why is it used for categorical variables?

Quick Overview

Asks what a factor is in R and why categorical variables are stored as factors. Tests knowledge of integer codes and levels, how models and summaries treat factors, ordered factors, and the common conversion and subsetting pitfalls.

What is a factor in R, and why is it used for categorical variables?

Role: Data Scientist

Category: Data Manipulation (SQL/Python)

Difficulty: easy

Interview Round: Other

What is a factor in R, and why is it used for categorical variables? ```hint Look under the hood Call `unclass()` on a small factor and compare what you see with what `print()` shows. Then think about what a model function would do with each of the two views. ``` ### What a Strong Answer Covers - How a factor is stored, and how its levels are ordered when you do not specify them. - What a fixed set of levels does for data validity. - How modeling and summary functions treat factors, including which level becomes the baseline. - Ordered factors and when to use them. - The usual conversion and subsetting pitfalls. ### Follow-up Questions - How do you change the reference level of a factor before fitting `lm()`, and why would you want to? - After filtering a data frame, `table()` still lists categories with zero counts. Why, and how do you remove them? - Which contrasts does `lm()` use for an ordered factor by default, and how does that change the coefficients you see? - When would you leave a categorical column as character and not convert it to a factor?

Overview: Asks what a factor is in R and why categorical variables are stored as factors. Tests knowledge of integer codes and levels, how models and summaries treat factors, ordered factors, and the common conversion and subsetting pitfalls.

Nov 25, 2026
easyData ScientistOtherData Manipulation (SQL/Python)
0
0

What is a factor in R, and why is it used for categorical variables?

What a Strong Answer Covers Guidance

  • How a factor is stored, and how its levels are ordered when you do not specify them.
  • What a fixed set of levels does for data validity.
  • How modeling and summary functions treat factors, including which level becomes the baseline.
  • Ordered factors and when to use them.
  • The usual conversion and subsetting pitfalls.

Follow-up Questions Guidance

  • How do you change the reference level of a factor before fitting lm() , and why would you want to?
  • After filtering a data frame, table() still lists categories with zero counts. Why, and how do you remove them?
  • Which contrasts does lm() use for an ordered factor by default, and how does that change the coefficients you see?
  • When would you leave a categorical column as character and not convert it to a factor?