在 r 中以零索引方式将因子 class 转换为数字

Converting factor class to numeric in a zero indexed fashion in r

将数据框中的因子 class 列转换为数字时,列中的各个级别将根据我理解的字母顺序转换为整数。有没有办法将它们转换为从0开始的整数。下面是一个示例代码:

target <- as.factor(c("<50", ">=50",">=50",">=50","<50"))
feat1 <- as.numeric(c(1,2,3,4,5))
feat2 <- as.factor(c("cat", "dog", "monkey","seal", "monkey"))

dat <- data.frame(feat1, feat2, target)

dat

for(col in names(dat)){
  if(class(dat[[col]]) == "factor"){
    dat[[col]] <- as.numeric(dat[[col]])
  }
}

使用dplyr

library(dplyr)

dat %>% 
  mutate(across(where(is.factor), ~ as.numeric(.) - 1))

或以 R 为基数:

dat[] <- lapply(dat, function(x) if (is.factor(x)) as.numeric(x) - 1 else x)

输出

  feat1 feat2 target
1     1     0      0
2     2     1      1
3     3     2      1
4     4     3      1
5     5     2      0

使用data.table

library(data.table)
nm1 <- names(sapply(dat, is.factor))
setDT(dat)[, (nm1) := lapply(.SD, as.numeric) - 1, .SDcols = nm1]