【问题标题】:Replace factors with a numeric value用数值替换因子
【发布时间】:2021-02-16 02:37:17
【问题描述】:

我有一个数据框,其中每一列都是类型因子,并且有超过 3000 个级别。 有没有办法可以用数值替换每个级别。 考虑内置数据框 InsectSprays

> str(InsectSprays)
'data.frame':   72 obs. of  2 variables:
 $ count: num  10 7 20 14 14 12 10 23 17 20 ...
 $ spray: Factor w/ 6 levels "A","B","C","D",..: 1 1 1 1 1 1 1 1 1 1 ...

替换应该如下:

A=1,B=2,C=3,D=4,E=5,F=6。

如果有 3000 个级别:

"USA"=1,"UK"=2....,France="3000".

解决方案应该自动检测级别(例如:3000),然后从 1 到 3000 替换每个级别。

【问题讨论】:

    标签: r


    【解决方案1】:

    对于InsectSprays 示例,您可以使用:

    levels(InsectSprays$spray) <- 1:6
    

    应该概括您的问题。

    【讨论】:

      【解决方案2】:

      因子变量已经具有对应于每个因子水平的基础数值。你可以看到如下:

      as.numeric(InsectSprays$spray)
      

      x = factor(c("A","D","B","G"))
      as.numeric(x)
      

      如果您想添加与每个级别对应的特定数值,例如,您可以从查找表中合并这些值:

      # Create a lookup table with the numeric values you want to correspond to each level of spray
      lookup = data.frame(spray=levels(InsectSprays$spray), sprayNumeric=c(5,4,1,2,3,6))
      
      # Merge lookup values into your data frame
      InsectSprays = merge(InsectSprays, lookup, by="spray")
      

      【讨论】:

        【解决方案3】:

        根据本教程 (https://statisticsglobe.com/how-to-convert-a-factor-to-numeric-in-r/),我使用以下代码将因子水平转换为特定数字

        levels(InsectSprays$spray) # to check the order levels are stored
        
        levels(InsectSprays$spray) <- c(0, 1, 2, 3, 4, 5) # assign the number I want to each level 
        
        InsectSprays$spray <- as.numeric(as.character(InsectSprays$spray)) # to change from factor to numeric
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-05-14
          • 1970-01-01
          • 1970-01-01
          • 2021-05-03
          • 2018-06-13
          • 2016-09-30
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多