当我将因子转换为数字或整数时,我得到的是底层的级别代码,而不是数字形式的值。

f <- factor(sample(runif(5), 20, replace = TRUE))
##  [1] 0.0248644019011408 0.0248644019011408 0.179684827337041 
##  [4] 0.0284090070053935 0.363644931698218  0.363644931698218 
##  [7] 0.179684827337041  0.249704354675487  0.249704354675487 
## [10] 0.0248644019011408 0.249704354675487  0.0284090070053935
## [13] 0.179684827337041  0.0248644019011408 0.179684827337041 
## [16] 0.363644931698218  0.249704354675487  0.363644931698218 
## [19] 0.179684827337041  0.0284090070053935
## 5 Levels: 0.0248644019011408 0.0284090070053935 ... 0.363644931698218

as.numeric(f)
##  [1] 1 1 3 2 5 5 3 4 4 1 4 2 3 1 3 5 4 5 3 2

as.integer(f)
##  [1] 1 1 3 2 5 5 3 4 4 1 4 2 3 1 3 5 4 5 3 2

我不得不求助于粘贴来获得实际值:

as.numeric(paste(f))
##  [1] 0.02486440 0.02486440 0.17968483 0.02840901 0.36364493 0.36364493
##  [7] 0.17968483 0.24970435 0.24970435 0.02486440 0.24970435 0.02840901
## [13] 0.17968483 0.02486440 0.17968483 0.36364493 0.24970435 0.36364493
## [19] 0.17968483 0.02840901

有没有更好的方法将因数转换为数字?


当前回答

如果有数据帧,可以使用hablar::convert。语法很简单:

样本df

library(hablar)
library(dplyr)

df <- dplyr::tibble(a = as.factor(c("7", "3")),
                    b = as.factor(c("1.5", "6.3")))

解决方案

df %>% 
  convert(num(a, b))

给你:

# A tibble: 2 x 2
      a     b
  <dbl> <dbl>
1    7.  1.50
2    3.  6.30

或者如果你想让一列是整数,一列是数字:

df %>% 
  convert(int(a),
          num(b))

结果:

# A tibble: 2 x 2
      a     b
  <int> <dbl>
1     7  1.50
2     3  6.30

其他回答

R有许多(未记录的)便利函数用于转换因子:

as.character.factor as.data.frame.factor as.Date.factor as.list.factor as.vector.factor ...

但令人烦恼的是,没有任何东西可以处理因子->数字转换。作为Joshua Ulrich回答的延伸,我建议通过定义你自己的惯用函数来克服这个遗漏:

as.double.factor <- function(x) {as.numeric(levels(x))[x]}

你可以把它存储在你的脚本开头,或者更好的存储在你的。rprofile文件中。

注意:这个特殊的答案不是用于将数值因子转换为数字,而是用于将分类因子转换为相应的级别数字。


这篇文章中的每个答案都没有为我产生结果,NAs正在生成。

y2<-factor(c("A","B","C","D","A")); 
as.numeric(levels(y2))[y2] 
[1] NA NA NA NA NA Warning message: NAs introduced by coercion

对我有用的是——

as.integer(y2)
# [1] 1 2 3 4 1

如果因子级别是整数,则Strtoi()有效。

如果你有很多因子列要转换成数字,

df <- rapply(df, function(x) as.numeric(levels(x))[x], "factor", how =  "replace")

这个解决方案对于包含混合类型的data.frames是健壮的,前提是所有的因子级别都是数字。

从我能读到的许多答案中,唯一给出的方法是根据因素的数量扩大变量的数量。如果你有一个级别为“dog”和“cat”的变量“pet”,你最终会得到pet_dog和pet_cat。

在我的例子中,我希望保持相同数量的变量,通过将因子变量转换为数值变量,以一种可以应用于许多级别的许多变量的方式,例如cat=1和dog=0。

对应的解决方案如下:

crime <- data.frame(city = c("SF", "SF", "NYC"),
                    year = c(1990, 2000, 1990),
                    crime = 1:3)

indx <- sapply(crime, is.factor)

crime[indx] <- lapply(crime[indx], function(x){ 
  listOri <- unique(x)
  listMod <- seq_along(listOri)
  res <- factor(x, levels=listOri)
  res <- as.numeric(res)
  return(res)
}
)