在 R中将分类变量转换为数字

我有一个巨大的数据库,我有很多分类变量。

我有一个巨大的数据库,我有很多分类变量。

> M=data.frame(Type_peau,PEAU_CORPS,SENSIBILITE,IMPERFECTIONS,BRILLANCE ,GRAIN_PEAU,RIDES_VISAGE,ALLERGIES,MAINS,
+              INTERET_ALIM_NATURELLE,INTERET_ORIGINE_GEO,INTERET_VACANCES,INTERET_COMPOSITION,DataQuest1,Priorite2,
+              Priorite1,DataQuest4,Age,Nbre_gift,w,Nbre_achat)
> # pour voir s'il y a des données manquantes
> str(M)
'data.frame':   836 obs. of  21 variables:
 $ Type_peau             : Factor w/ 5 levels "","Grasse","Mixte",..: 3 4 5 3 4 3 3 3 2 3 ...
 $ PEAU_CORPS            : Factor w/ 4 levels "","Normale","Sèche",..: 2 3 3 2 2 2 3 2 3 2 ...
 $ SENSIBILITE           : Factor w/ 4 levels "","Aucune","Fréquente",..: 4 4 4 2 4 3 4 2 4 4 ...
 $ IMPERFECTIONS         : Factor w/ 4 levels "","Fréquente",..: 3 4 3 4 3 2 3 4 3 3 ...
 $ BRILLANCE             : Factor w/ 4 levels "","Aucune","Partout",..: 4 2 2 4 4 4 4 4 3 4 ...
 $ GRAIN_PEAU            : Factor w/ 4 levels "","Dilaté","Fin",..: 4 4 4 2 4 2 4 4 2 4 ...
 $ RIDES_VISAGE          : Factor w/ 4 levels "","Aucune","Très visibles",..: 2 2 2 4 4 2 4 2 4 2 ...
 $ ALLERGIES             : Factor w/ 4 levels "","Non","Oui",..: 2 2 2 2 2 2 2 2 2 2 ...
 $ MAINS                 : Factor w/ 4 levels "","Moites","Normales",..: 3 4 4 3 3 3 3 4 4 4 ...
 $ INTERET_ALIM_NATURELLE: Factor w/ 4 levels "","Beaucoup",..: 2 4 4 4 2 2 2 4 4 2 ...
 $ INTERET_ORIGINE_GEO   : Factor w/ 5 levels "","Beaucoup",..: 2 4 2 5 2 2 2 2 2 2 ...
 $ INTERET_VACANCES      : Factor w/ 6 levels "","À la mer",..: 3 4 2 2 3 2 3 2 3 2 ...
 $ INTERET_COMPOSITION   : Factor w/ 4 levels "","Beaucoup",..: 2 2 2 4 2 2 2 2 4 2 ...
 $ DataQuest1            : Factor w/ 4 levels "-20","20-30",..: 4 3 4 4 4 3 3 2 3 2 ...
 $ Priorite2             : Factor w/ 7 levels "éclatante","hydratée",..: 3 1 3 4 3 2 7 1 4 6 ...
 $ Priorite1             : Factor w/ 7 levels "éclatante","hydratée",..: 4 6 1 5 1 6 1 2 6 4 ...
 $ DataQuest4            : Factor w/ 2 levels "nature","urbain": 2 2 2 2 2 1 2 2 2 2 ...
 $ Age                   : int  32 37 23 44 33 30 43 43 60 31 ...
 $ Nbre_gift             : int  1 4 1 1 2 1 1 1 1 1 ...
 $ w                     : num  0.25 0.25 0.5 0.25 0.5 0 0 0 0 0.75 ...
 $ Nbre_achat            : int  3 4 7 3 6 9 22 13 7 16 ...

我需要将所有分类变量自动转换为数字。例如,对于变量Type_peau,它是:

 head(Type_peau)
[1] Mixte   Normale Sèche   Mixte   Normale Mixte  
Levels:  Grasse Mixte Normale Sèche

我想要它:

head(Type_peau)
[1] 2 3 4 2 3 2
Levels: 1 2 3 4

我怎样才能自动为所有分类变量?

15

可以使用unclass()显示因子变量的数值:

Type_peau<-as.factor(c("Mixte","Normale","Sèche","Mixte","Normale","Mixte"))
Type_peau
unclass(Type_peau)

要对所有分类变量执行此操作,可以使用sapply()

must_convert<-sapply(M,is.factor)       # logical vector telling if a variable needs to be displayed as numeric
M2<-sapply(M[,must_convert],unclass)    # data.frame of all categorical variables now displayed as numeric
out<-cbind(M[,!must_convert],M2)        # complete data.frame with all variables put together

编辑:A5C1D2H2I1M1N2O1R2T1's solution一步工作:

out<-data.matrix(M)

它只适用于你的 data.frame 不包含任何字符变量(否则,它们将被放入 NA)。

9

也许你在data.matrix之后。从函数的描述:

返回通过将数据框中的所有变量转换为数字模式,然后将它们绑定在一起作为矩阵的列而获得的矩阵。因子和有序因子由其内部代码替换。

例子:

mydf <- data.frame(A = letters[1:5],
                   B = LETTERS[1:5],
                   C = month.abb[1:5],
                   D = 1:5)
str(mydf)
# 'data.frame': 5 obs. of  4 variables:
#  $ A: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
#  $ B: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
#  $ C: Factor w/ 5 levels "Apr","Feb","Jan",..: 3 2 4 1 5
#  $ D: int  1 2 3 4 5
data.matrix(mydf)
#      A B C D
# [1,] 1 1 3 1
# [2,] 2 2 2 2
# [3,] 3 3 4 3
# [4,] 4 4 1 4
# [5,] 5 5 5 5

将其全部替换为:

mydf[] <- data.matrix(mydf)
mydf
#   A B C D
# 1 1 1 3 1
# 2 2 2 2 2
# 3 3 3 4 3
# 4 4 4 1 4
# 5 5 5 5 5

当然,如果您有更多列类型,则必须首先决定如何处理它们。例如,有一个问题是,如果有一个character列,data.matrix将导致一列NA值,这是正确的。但是,正确的问题应该是“您想如何处理character列?

这里有两个选项。您可以类似地扩展其他列类型的逻辑。

mydf <- data.frame(A = letters[1:5],
                   B = LETTERS[1:5],
                   C = month.abb[1:5],
                   D = 1:5)
mydf$E <- state.abb[1:5]
str(mydf)
# 'data.frame': 5 obs. of  5 variables:
#  $ A: Factor w/ 5 levels "a","b","c","d",..: 1 2 3 4 5
#  $ B: Factor w/ 5 levels "A","B","C","D",..: 1 2 3 4 5
#  $ C: Factor w/ 5 levels "Apr","Feb","Jan",..: 3 2 4 1 5
#  $ D: int  1 2 3 4 5
#  $ E: chr  "AL" "AK" "AZ" "AR" ...
## You want to convert everything to numeric
data.matrix(data.frame(unclass(mydf))) 
#      A B C D E
# [1,] 1 1 3 1 2
# [2,] 2 2 2 2 1
# [3,] 3 3 4 3 4
# [4,] 4 4 1 4 3
# [5,] 5 5 5 5 5
## You only want to convert factors to numeric
mydf[sapply(mydf, is.factor)] <- data.matrix(mydf[sapply(mydf, is.factor)])
mydf
#   A B C D  E
# 1 1 1 3 1 AL
# 2 2 2 2 2 AK
# 3 3 3 4 3 AZ
# 4 4 4 1 4 AR
# 5 5 5 5 5 CA
5
library(dplyr)
mydf <- data.frame(A = letters[1:5],
                   B = LETTERS[1:5],
                   C = month.abb[1:5],
                   D = 1:5)
glimpse(mydf)
# Observations: 5
# Variables: 4
# $ A <fctr> a, b, c, d, e
# $ B <fctr> A, B, C, D, E
# $ C <fctr> Jan, Feb, Mar, Apr, May
# $ D <int> 1, 2, 3, 4, 5

dplyr中使用谓词函数

mydf %>% mutate_if(is.factor, as.numeric)
#  A B C D
# 1 1 1 3 1
# 2 2 2 2 2
# 3 3 3 4 3
# 4 4 4 1 4
# 5 5 5 5 5
4

as.numeric也是这样做的。

df <- iris
df$newgroup <- as.factor(rep(c(letters[1:10]))) # just another factor
str(df) # Species and newgroup are categorial variables
as.numeric(df$Species) # this returns the levels (numeric) of Species.
                       # Now, we want to apply this automatically to all
                       # categorical variables
# using lapply
i <- sapply(df, is.factor)
df[i] <- lapply(df[i], as.numeric)
str(df)
# using dplyr
#(load df again)
library(dplyr)
df2 <- df %>% mutate_if(is.factor, as.numeric)
str(df2)
# using purrr
library(purrr)
df3 <- df %>% map_if(is.factor, as.numeric)
str(df3)

如果您还想创建假人变量,请尝试

library(dummies)
df.4 <- dummy.data.frame(df, sep = ".")

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(874)
什么是Java中的哈希函数
上一篇
String buffer:Java StringBuffer在扩展后不会更改引用
下一篇

相关推荐

  • Rfid管理系统:斑马非RFID打印机:发送RFID命令的后果

    关于Rfid管理系统的问题,在zebra technologies rfid中经常遇到,我正在一个 RFID 试点项目中工作,该项目要求我编辑一个 ZPL 文件,以包含要发送到 RFID 打印机的 RFID 命令。(“^ RF”在 ZPL 语言中编码 RFID 标签)…

    2022-12-18 15:30:06
    0 72 77
  • 在 R中将平均值插入散点图

    我将在下面插入两个代码,第一个生成一个散点图,其中考虑了我的数据库中的所选日期 (date2)。下载数据库的链接是:https://docs.google.com/spreadsheets/d/1W_hzuRq7D6X12BdwaXeM-cjg2A5MIKDx/edit?usp=sharing&ouid=102073768617937039119&rtpof=true&sd=true。无论如何,我将在此消息的末尾插入我的数据库映像。…

    2022-11-11 15:16:21
    0 26 12
  • 最小系统:最小化应用程序到系统托盘(desktop tray)

    关于最小系统的问题,在desktop tray中经常遇到,我有一个由 C # 和 Visual Studio 2010 提供支持的 Windows 窗体应用程序。…

    2022-11-29 01:33:21
    0 33 61
  • Dg分区:路由器访问在ArrisDG1670A上不起作用

    关于Dg分区的问题,在arris router remote access中经常遇到,不确定这是否仅用于编程,但无论如何我都会问。我有一个 Arris DG1670A 路由器,正在尝试设置远程访问。我没有像某些路由器那样启用远程访问的选项卡或部分。我尝试设置虚拟服务器 / 端口转发和端口触发器,这是我在路由器设置中看到的最接近远程访问的设置,但是当我检查我设置的端口是否在 canyouseemports.is 上打开时。…

    2022-12-10 06:15:00
    0 24 93
  • 如何在 log-logsns.regplot中实现直线回归线

    我试图在 Python 中重新创建这个用 R 创建的情节:…

    2022-12-12 01:16:38
    0 79 56
  • 将“page-break-before”应用于表行 (tr)

    根据 W3.org,样式page-break-after适用于块级元素(http://www.w3.org/TR/2004/CR-CSS21-20040225/page.html#page-break-props)…

    2022-12-07 00:45:20
    0 74 97
  • 使用ggplot2在R中的 Barplot中的垂直平均线

    我对 R 很新,但我试图从 ggplot2 库中创建一个 barplot 中的垂直平均线。…

    2022-11-11 15:12:11
    0 11 53

发表评论

登录 后才能评论

评论列表(33条)