3

I have a column in my data frame that is numbers 1, 2, 3, until 31.

column is titled 'game'

R tells me this column consists of Factors with 31 levels.

enter image description here

How do I convert the factors to numbers without it displaying the levels so I can analyze it numerically?

I'm using R studio if that help at all.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
dudemcgregor
  • 69
  • 2
  • 2
  • 6

2 Answers2

19

If you convert directly from factor to numeric, it will return the levels instead of the actual values. Here it doesn't matter, because it looks like the levels and the values are the same. If they are different, you have to convert to character first, and then to numeric.

df$game <- as.numeric(as.character(df$game))
ytk
  • 2,787
  • 4
  • 27
  • 42
0

If you have a dataframe of factors with the same type of data in each column, then you can just use as.matrix:

> e=expand.grid(list(letters[1:2],letters[1:3]))
> str(e)
'data.frame':   6 obs. of  2 variables:
 $ Var1: Factor w/ 2 levels "a","b": 1 2 1 2 1 2
 $ Var2: Factor w/ 3 levels "a","b","c": 1 1 2 2 3 3
 - attr(*, "out.attrs")=List of 2
  ..$ dim     : int [1:2] 2 3
  ..$ dimnames:List of 2
  .. ..$ Var1: chr [1:2] "Var1=a" "Var1=b"
  .. ..$ Var2: chr [1:3] "Var2=a" "Var2=b" "Var2=c"
> str(as.matrix(e))
 chr [1:6, 1:2] "a" "b" "a" "b" "a" "b" "a" "a" "b" "b" "c" "c"
 - attr(*, "dimnames")=List of 2
  ..$ : NULL
  ..$ : chr [1:2] "Var1" "Var2"
nisetama
  • 7,764
  • 1
  • 34
  • 21