R:使用cross()编码分类数据

R:使用cross()编码分类数据,r,encoding,pipeline,categorical-data,dummy-variable,R,Encoding,Pipeline,Categorical Data,Dummy Variable,我有一个数据集,其特征类型为character(并非所有特征都是二进制的,其中一个表示一个区域) 为了避免多次使用该函数,我尝试使用pipeline和cross()来标识字符类型的所有列,并使用创建的函数对它们进行编码 encode_ordinal <- function(x, order = unique(x)) { x <- as.numeric(factor(x, levels = order, exclude = NULL)) x } dataset <- d

我有一个数据集,其特征类型为character(并非所有特征都是二进制的,其中一个表示一个区域)

为了避免多次使用该函数,我尝试使用pipeline和cross()来标识字符类型的所有列,并使用创建的函数对它们进行编码

encode_ordinal <- function(x, order = unique(x)) {
  x <- as.numeric(factor(x, levels = order, exclude = NULL))
  x
}

dataset <- dataset %>% 
  encode_ordinal(across(where(is.character)))

encode_ordinal您应该在
encode_ordinal
内部调用
mutate
,如以下示例所示:

dataset <- tibble(x = 1:3, y = c('a', 'b', 'b'), z = c('A', 'A', 'B'))
# # A tibble: 3 x 3
#       x y     z    
#   <int> <chr> <chr>
# 1     1 a     A    
# 2     2 b     A    
# 3     3 b     B    

dataset %>%
    mutate(across(where(is.character), encode_ordinal))
# # A tibble: 3 x 3
#       x     y     z
#   <int> <dbl> <dbl>
# 1     1     1     1
# 2     2     2     1
# 3     3     2     2
dataset%
变异(交叉(其中(是字符),按顺序编码)
##tibble:3 x 3
#x y z
#     
# 1     1     1     1
# 2     2     2     1
# 3     3     2     2