1

I am just starting to learn R and been trying to use factors and levels for categorical data.

A simple example:

survey_vector <- c("M", "F", "F", "M", "M")
factor_survey_vector <- factor(survey_vector)
levels(factor_survey_vector) <- c("Female", "Male")
factor_survey_vector

This works fine and I get the output as:

[1] Male Female Female Male Male
Levels: Female Male

However, here I have to specify the levels in the sorted order and I would like it to be more explicit. I tried something like:

levels(factor_survey_vector) <- c(M="Male", F="Female")

However, this does not work as expected.

Luca
  • 10,458
  • 24
  • 107
  • 234
  • hmmmmm... seems that I need to provide them sorted in some way which is really annoying if you have many labels. I thought there must be a way to do so without having to order it. it is also a problem if I get a new label and then I need to add it at the correct location... – Luca Sep 01 '15 at 13:33

1 Answers1

4

From ?levels, important points bolded:

Usage

levels(x)

levels(x) <- value

Arguments

x an object, for example a factor.

value A valid value for levels(x). For the default method, NULL or a character vector. For the factor method, a vector of character strings with length at least the number of levels of x, or a named list specifying how to rename the levels.

In the examples there is a sample usage:

## same, using a named list
z <- gl(3, 2, 12)
levels(z) <- list(A = c(1,3), B = 2)
z

And as commenting I misread it and took it in the wrong way, the new level name is the left part of the assignment, the documentation has no ambiguity about this.

So to achieve the goal in this question this do the trick:

levels(factor_survey_vector) <- list(Male="M",Female="F")
MichaelChirico
  • 33,841
  • 14
  • 113
  • 198
Tensibai
  • 15,557
  • 1
  • 37
  • 57
  • 2
    I'll also add that `relevel` may also serve the purpose more generally--it's tailored to when you want _one_ of perhaps _many_ levels to be sorted first (i.e., to set a reference level). – MichaelChirico Sep 01 '15 at 13:50