[英]R: Encoding categorical data using across()
我有一個具有字符類型特征的數據集(並非所有都是二進制的,其中一個代表一個區域)。
為了避免不得不多次使用 function,我嘗試使用管道和 cross() 來識別所有字符類型的列,並使用創建的 function 對它們進行編碼。
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)))
但是,當我收到錯誤消息時,似乎我沒有正確使用 cross():
錯誤:cross across()
只能在 dplyr 動詞中使用。
我想知道我是否過於復雜,有一種更簡單的方法可以實現這一點,即識別字符類型的所有特征並對其進行編碼。
您應該在mutate
中調用encode_ordinal
across
如下例所示:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.