我在R中有以下数据框

  ID      Season      Year       Weekday
  1       Winter      2017       Monday
  2       Winter      2018       Tuesday
  3       Summer      2017       Monday
  4       Summer      2018       Wednsday

我想将这些因子水平转换为整数,下面是我想要的数据框
  ID      Season      Year       Weekday
  1       1           1          1
  2       1           2          2
  3       2           1          1
  4       2           2          3

  Winter = 1,Summer =2
  2017 = 1 , 2018 = 2
  Monday = 1,Tuesday = 2,Wednesday = 3

目前,我正在为上面的3做ifelse
  otest_xgb$Weekday <- as.integer(ifelse(otest_xgb$Weekday == "Monday",1,
                                   ifelse(otest_xgb$Weekday == "Tuesday",2,
                                          ifelse(otest_xgb$Weekday == "Wednesday",3,
                                                 ifelse(otest_xgb$Weekday == "Thursday",4,5)))))

有什么办法可以避免写长ifelse吗?

最佳答案

我们可以将matchunique元素一起使用

library(dplyr)
dat %>%
      mutate_all(funs(match(., unique(.))))
#   ID Season Year Weekday
#1  1      1    1       1
#2  2      1    2       2
#3  3      2    1       1
#4  4      2    2       3

关于r - 如何在r中将因子水平转换为整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/51184569/

10-12 04:15