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.
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.
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))
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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.