recipes::step_num2factor() 尽管提供了足够的级别MWE 提供,但在烘焙时仍将最后一个级别保留为 NA

问题描述

我使用函数 step_num2factor() 创建的 last 类别正确创建了所有级别,但最后一个级别。在那里它填充了一个 NA。

MWE

test <- tibble(pred = c(0,1,2,3,4,5,8),target = c(0,0))

打印时看起来像这样:

# A tibble: 7 x 2
   pred target
  <dbl>  <dbl>
1     0      0
2     1      1
3     2      0
4     3      1
5     4      1
6     5      1
7     8      0

执行配方步骤并比较结果

test <- tibble(pred = c(0,0))

my_levels <- c("zero","one","two","three","four","five","eight")

recipe(target ~ pred,data = test) %>% 
step_num2factor(pred,levels = my_levels,transform = function(x) x + 1) %>% 
prep(training = test) %>% 
bake(new_data = test)

备注:变换是因为一个因子不能有0级。 (source)

准备和烘焙后转换后的数据集

# A tibble: 7 x 2
  pred  target
  <fct>  <dbl>
1 zero       0
2 one        1
3 two        0
4 three      1
5 four       1
6 five       1
7 NA         0

NA 不应该在那里。它应该是“八”类。我做错了什么?

备注:我也用“六”试过了,因为我认为该函数可能只接受单词中的值,而不是完全随机命名的级别,但也不是那样。

解决方法

您需要确保您的输入、级别和 transform 完美匹配。 您使用 transform = function(x) x + 1 是正确的,因为您正在尝试捕获 0。因此,当您的输入为 n 时,则选择 n+1levelsth 值。

当您的输入为 8 时,step_num2factor() 返回 8+1=9levelsth 值,该值不存在,因为它的长度仅为 7,导致您看到的 NA。下面的代码应该说明问题

library(recipes)

my_levels <- c("zero","one","two","three","four","five","eight")

test <- tibble(pred = c(0,1,2,3,4,5,6),target = c(0,0))

recipe(target ~ pred,data = test) %>% 
  step_num2factor(pred,levels = my_levels,transform = function(x) x + 1) %>% 
  prep() %>% 
  bake(new_data = NULL)
#> # A tibble: 7 x 2
#>   pred  target
#>   <fct>  <dbl>
#> 1 zero       0
#> 2 one        1
#> 3 two        0
#> 4 three      1
#> 5 four       1
#> 6 five       1
#> 7 eight      0

要解决您的问题,您需要确保 my_levels

中没有间隙
test <- tibble(pred = c(0,8),0))

my_levels <- c("zero","six","seven","eight","nine","ten")

recipe(target ~ pred,transform = function(x) x + 1) %>% 
  prep() %>% 
  bake(new_data = NULL)
#> # A tibble: 7 x 2
#>   pred  target
#>   <fct>  <dbl>
#> 1 zero       0
#> 2 one        1
#> 3 two        0
#> 4 three      1
#> 5 four       1
#> 6 five       1
#> 7 eight      0

reprex package (v0.3.0) 于 2021 年 3 月 27 日创建

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...