首页 文章

如何在不丢失信息的情况下将因子转换为整数\数字?

提问于
浏览
495

当我将因子转换为数字或整数时,我得到基础级别代码,而不是值作为数字 .

f <- factor(sample(runif(5), 20, replace = TRUE))
##  [1] 0.0248644019011408 0.0248644019011408 0.179684827337041 
##  [4] 0.0284090070053935 0.363644931698218  0.363644931698218 
##  [7] 0.179684827337041  0.249704354675487  0.249704354675487 
## [10] 0.0248644019011408 0.249704354675487  0.0284090070053935
## [13] 0.179684827337041  0.0248644019011408 0.179684827337041 
## [16] 0.363644931698218  0.249704354675487  0.363644931698218 
## [19] 0.179684827337041  0.0284090070053935
## 5 Levels: 0.0248644019011408 0.0284090070053935 ... 0.363644931698218

as.numeric(f)
##  [1] 1 1 3 2 5 5 3 4 4 1 4 2 3 1 3 5 4 5 3 2

as.integer(f)
##  [1] 1 1 3 2 5 5 3 4 4 1 4 2 3 1 3 5 4 5 3 2

我必须诉诸 paste 才能获得真正的 Value :

as.numeric(paste(f))
##  [1] 0.02486440 0.02486440 0.17968483 0.02840901 0.36364493 0.36364493
##  [7] 0.17968483 0.24970435 0.24970435 0.02486440 0.24970435 0.02840901
## [13] 0.17968483 0.02486440 0.17968483 0.36364493 0.24970435 0.36364493
## [19] 0.17968483 0.02840901

有没有更好的方法将因子转换为数字?

7 回答

  • 72

    最简单的方法是使用包varhandle中的 unfactor 函数

    unfactor(your_factor_variable)
    

    这个例子可以快速入门:

    x <- rep(c("a", "b", "c"), 20)
    y <- rep(c(1, 1, 0), 20)
    
    class(x)  # -> "character"
    class(y)  # -> "numeric"
    
    x <- factor(x)
    y <- factor(y)
    
    class(x)  # -> "factor"
    class(y)  # -> "factor"
    
    library(varhandle)
    x <- unfactor(x)
    y <- unfactor(y)
    
    class(x)  # -> "character"
    class(y)  # -> "numeric"
    
  • 27

    这篇文章中的每个答案都未能为我产生结果,NAs正在生成 .

    y2<-factor(c("A","B","C","D","A")); 
    as.numeric(levels(y2))[y2] 
    [1] NA NA NA NA NA Warning message: NAs introduced by coercion
    

    对我有用的是 -

    as.integer(y2)
    # [1] 1 2 3 4 1
    

    Note: this particular answer is not for converting numeric-valued factors to numerics, it is for converting categorical factors to their corresponding level numbers.

  • 589

    请参阅?factor的警告部分:

    特别是,as.numeric应用于一个因子是没有意义的,并且可能通过隐式强制发生 . 要将因子f转换为大约其原始数值,建议使用as.numeric(levels(f))[f],并且比as.numeric(as.character(f))稍微更有效 .

    关于R has similar advice的常见问题 .


    Why is as.numeric(levels(f))[f] more efficent than as.numeric(as.character(f))?

    as.numeric(as.character(f)) 实际上是 as.numeric(levels(f)[f]) ,因此您在 length(x) 值上执行转换为数字,而不是 nlevels(x) 值 . 对于具有较少水平的长矢量,速度差异将是最明显的 . 如果 Value 观大多是独一无二的,那么就会对此过于担忧 .


    Some timings

    library(microbenchmark)
    microbenchmark(
      as.numeric(levels(f))[f],
      as.numeric(levels(f)[f]),
      as.numeric(as.character(f)),
      paste0(x),
      paste(x),
      times = 1e5
    )
    ## Unit: microseconds
    ##                         expr   min    lq      mean median     uq      max neval
    ##     as.numeric(levels(f))[f] 3.982 5.120  6.088624  5.405  5.974 1981.418 1e+05
    ##     as.numeric(levels(f)[f]) 5.973 7.111  8.352032  7.396  8.250 4256.380 1e+05
    ##  as.numeric(as.character(f)) 6.827 8.249  9.628264  8.534  9.671 1983.694 1e+05
    ##                    paste0(x) 7.964 9.387 11.026351  9.956 10.810 2911.257 1e+05
    ##                     paste(x) 7.965 9.387 11.127308  9.956 11.093 2419.458 1e+05
    
  • -1

    R有许多(未记录的)便利函数用于转换因子:

    • as.character.factor

    • as.data.frame.factor

    • as.Date.factor

    • as.list.factor

    • as.vector.factor

    • ......

    但令人讨厌的是,没有什么可以处理因素 - >数字转换 . 作为Joshua Ulrich答案的延伸,我建议用你自己惯用函数的定义来克服这个遗漏:

    as.numeric.factor <- function(x) {as.numeric(levels(x))[x]}
    

    您可以在脚本的开头存储,或者甚至更好地存储在.Rprofile文件中 .

  • 7

    在因子标签与原始值匹配的情况下,可能 only . 我将用一个例子来解释它 .

    假设数据是vector x

    x <- c(20, 10, 30, 20, 10, 40, 10, 40)
    

    现在我将创建一个包含四个标签的因子:

    f <- factor(x, levels = c(10, 20, 30, 40), labels = c("A", "B", "C", "D"))
    

    1) x 是double类型, f 是类型integer . 这是第一次不可避免的信息丢失 . 因子总是存储为整数 .

    > typeof(x)
    [1] "double"
    > typeof(f)
    [1] "integer"
    

    2)无法恢复到仅有 f 可用的原始值(10,20,30,40) . 我们可以看到 f 仅包含整数值1,2,3,4和两个属性 - 标签列表("A","B","C","D")和类属性"factor" . 而已 .

    > str(f)
     Factor w/ 4 levels "A","B","C","D": 2 1 3 2 1 4 1 4
    > attributes(f)
    $levels
    [1] "A" "B" "C" "D"
    
    $class
    [1] "factor"
    

    要恢复原始值,我们必须知道创建因子时使用的级别值 . 在这种情况下 c(10, 20, 30, 40) . 如果我们知道原始级别(按正确顺序),我们可以恢复原始值 .

    > orig_levels <- c(10, 20, 30, 40)
    > x1 <- orig_levels[f]
    > all.equal(x, x1)
    [1] TRUE
    

    这仅适用于为原始数据中的所有可能值定义标签的情况 .

    因此,如果您需要原始值,则必须保留它们 . 否则,很有可能只能从一个因素回到它们 .

  • 0

    如果您有数据框,则可以使用 hablar::convert . 语法很简单:

    Sample df

    library(hablar)
    library(dplyr)
    
    df <- dplyr::tibble(a = as.factor(c("7", "3")),
                        b = as.factor(c("1.5", "6.3")))
    

    Solution

    df %>% 
      convert(num(a, b))
    

    给你:

    # A tibble: 2 x 2
          a     b
      <dbl> <dbl>
    1    7.  1.50
    2    3.  6.30
    

    或者,如果您希望一列为整数和一个数字:

    df %>% 
      convert(int(a),
              num(b))
    

    结果是:

    # A tibble: 2 x 2
          a     b
      <int> <dbl>
    1     7  1.50
    2     3  6.30
    
  • 15

    在游戏后期,我发现 trimws() 可以将 factor(3:5) 转换为 c("3","4","5") . 然后你可以拨打 as.numeric() . 那是:

    as.numeric(trimws(x_factor_var))
    

相关问题