6

I have an R dataframe where one of the columns is a factor whose levels have an implicit ordering. How can I convert the factor levels to specific integers in the following manner:

  • "Strongly disagree" --> 1
  • "Somewhat disagree" --> 2
  • "Neutral" --> 3
  • "Somewhat agree" --> 4
  • "Strongly agree" --> 5

For example, here is my data frame:

agree <- c("Strongly agree", "Somewhat disagree", "Somewhat agree",
           "Neutral", "Strongly agree", "Strongly disagree", "Neutral")
age <- c(41, 35, 29, 42, 31, 22, 58)

df <- data.frame(age, agree)
df
#   age             agree
# 1  41    Strongly agree
# 2  35 Somewhat disagree
# 3  29    Somewhat agree
# 4  42           Neutral
# 5  31    Strongly agree
# 6  22 Strongly disagree
# 7  58           Neutral

str(df)
# 'data.frame': 7 obs. of  2 variables:
#  $ age  : num  41 35 29 42 31 22 58
#  $ agree: Factor w/ 5 levels "Neutral","Somewhat agree",..: 4 3 2 1 4 5 1

Now, I would like to convert the agree column to be an integer column using the mapping that I showed above.

I already searched these other questions about converting factor to integer, but they do not related to maintaining the factor ordering.

"How to convert a factor to an integer\numeric without a loss of information?"

"Convert factor to integer"

"Convert factor to integer in a data frame"

smci
  • 32,567
  • 20
  • 113
  • 146
stackoverflowuser2010
  • 38,621
  • 48
  • 169
  • 217
  • This question should help: http://stackoverflow.com/q/37431872/2372064 but the idea is just specify the `levels=` of the factor. – MrFlick Jul 27 '16 at 19:17
  • 1
    You can set the levels of factor variable by specifying the `levels` parameter when constructing it. `as.integer(factor(..., levels = ...))`. – Psidom Jul 27 '16 at 19:17

3 Answers3

9

You need to define the order of factors first:

ordering <- c("Strongly disagree", "Somewhat disagree", "Neutral", "Somewhat agree", "Strongly agree")

Then, when you first create your factor, you should use that definition:

agreeFactor <- factor(agree, levels = ordering)

Then, you should be able to get your ordered factor:

as.numeric(agreeFactor)

You can also just apply the order when using as.numeric(), but this can lead to inconsistencies if you decide to later retrieve your numeric vector and forget to apply the "levels = " argument.

e: If you want to directly import the numeric into your dataframe, simply use:

df$agree <- as.numeric(factor(df$agree, levels = ordering))
stackoverflowuser2010
  • 38,621
  • 48
  • 169
  • 217
tluh
  • 668
  • 1
  • 5
  • 16
  • So in my original code, would I use: `df$agree <- as.numeric(factor(df$agree, levels = ordering))` ? – stackoverflowuser2010 Jul 27 '16 at 19:57
  • Yup. You could also use `df <- data.frame(age, agreeFactor)` – tluh Jul 27 '16 at 20:14
  • 1
    I still need to call `as.numeric` to convert `agreeFactor` to an integer, right? – stackoverflowuser2010 Jul 27 '16 at 20:15
  • If you want to insert it into your dataframe as an integer, then yes, you need to do so. `df <- data.frame(age, as.numeric(agreeFactor))` could work if you set up the factor ordering ahead of time. – tluh Jul 27 '16 at 20:17
  • 1
    Yes, my original question was indeed: "Convert factor to integer while maintaining factor level ordering". Along those lines, maybe you can edit your answer to make it more robust so that it will help others who are reading it. – stackoverflowuser2010 Jul 27 '16 at 20:27
2

If your factor is already ordered with levels you can use the following function to convert that factor into the numerical order.

Convert_Numeric = function(X) {
        L = levels(X)
        Y = as.numeric(factor(X, labels = seq(1:length(L))))
        return(Y)
}

This can be particularly useful with functions or with dplyr:

df %>%
       mutate(Numeric_version = Convert_Numeric(agree))
Curtis
  • 159
  • 7
1

The dplyr library has a useful revalue function for this type of operation:

library(plyr)
df$agree<-as.numeric( revalue(df$agree, c("Strongly disagree" = 1,
                     "Somewhat disagree" = 2,
                     "Neutral" = 3,
                     "Somewhat agree" = 4,
                     "Strongly agree" = 5)) )

Overall @tluh method of ordering the factors is a better approach since it maintains the original input and sets the factors into the correct order.

Dave2e
  • 22,192
  • 18
  • 42
  • 50
  • why relevel when you could just specify the order? `as.numeric(factor(df$agree, c("Strongly disagree", "Somewhat disagree", "Neutral", "Somewhat agree", "Strongly agree")))` – pdb Apr 12 '17 at 05:34