0

(I am working in R 3.02 OSX.)

I have a data set where the variable of interest is imported as an int with values of 1, 2, 3 and they represent educational level.

Before conversion it was

 str(df$var)
 int [1:5000] 1 1 1 2 2 2 2 3 2 3 ...

I tried to create an ordered factor:

var_name <- ordered(df$var, levels = c(1,2,3), 
                    labels = c("Undergraduate Degree", "Graduate Degree", 
                               "Professional Degree"))

The variable is changed to a ordered factor with three levels (I see that in the str function). However all the values are now gone and replaced with all NAs.

I am able to get what I want by simply changing ordered() to factor():

var_name <- factor(df$var, levels = c(1,2,3), 
                   labels = c("Undergraduate Degree", "Graduate Degree", 
                              "Professional Degree"))

However, I am curious why does ordered() remove all the values? What did I do wrong in that function?

Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
mpg
  • 3,679
  • 8
  • 36
  • 45
  • 1
    Can you show us `str(df$var)`? Why is one data frame `df` and another `DF`? – josliber Jan 20 '14 at 01:41
  • df and DF are just typo. Both are the same dataframe$variable. – mpg Jan 20 '14 at 01:47
  • str(UniversalBank$Education) Ord.factor w/ 3 levels "Undergrad"<"Graduate"<..: NA NA NA NA NA NA NA NA NA NA ... – mpg Jan 20 '14 at 01:48
  • 3
    On a simplified example like `df <- data.frame(var=as.integer(c(1:3,2:3,1,NA)))`, your code for `var_name` works perfectly. – thelatemail Jan 20 '14 at 01:51
  • @mylesg please show us the variable before you convert to a factor. Your code expects a variable to have values 1, 2, and 3 in the original data frame. Please just edit your question to include `str(df$var)` before conversion to factor. – josliber Jan 20 '14 at 01:59
  • Here it is before conversion. str(UniversalBank$Education) int [1:5000] 1 1 1 2 2 2 2 3 2 3 ... – mpg Jan 20 '14 at 05:53
  • 1
    I can't reproduce this. Please create a [reproducible example](http://stackoverflow.com/q/5963269/1412059). – Roland Jan 20 '14 at 08:49

0 Answers0