简体   繁体   English

r - 将因子转换为数字并删除级别

[英]r - convert factor to numeric and remove levels

I have a column in my data frame that is numbers 1, 2, 3, until 31.我的数据框中有一列是数字 1、2、3,直到 31。

column is titled 'game'列标题为“游戏”

R tells me this column consists of Factors with 31 levels. R 告诉我这一列由 31 个级别的因素组成。

在此处输入图像描述

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.如果有帮助的话,我正在使用 R 工作室。

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 :如果您有一个 dataframe 的因子在每列中具有相同类型的数据,那么您可以使用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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM