【问题标题】:R Code Categorical Variable to 1 and 0 [duplicate]R代码分类变量为1和0 [重复]
【发布时间】:2016-11-24 07:16:06
【问题描述】:

有没有一种简单的方法可以将 2 级分类变量转换为二进制,然后更改列名?例如:如果我有“性别”变量,我将如何轻松地将女性编码为 1,男性编码为 0,并将列名更改为 isFemale?先感谢您。

【问题讨论】:

  • 一种方法是yourdata$isFemale <- as.integer(yourdata$yourvariable == "female")这个问题会有几个骗子
  • 如果它已经是 factor 类,那么 as.integer(yourdata$yourcolumn)as.numeric(yourdata$yourcolumn) 将起作用。至于更改列名,请参阅可用的介绍性材料,例如R tag info 上提供的材料。

标签: r binary


【解决方案1】:
df <- data.frame(Lett=letters[1:6], Gender = c("F","M","M","M","F","M"))
df
#   Lett Gender
# 1    a      F
# 2    b      M
# 3    c      M
# 4    d      M
# 5    e      F
# 6    f      M



levels(df$Gender) <- c(1,0)
df
#   Lett Gender
# 1    a      1
# 2    b      0
# 3    c      0
# 4    d      0
# 5    e      1
# 6    f      0

names(df)[2] <- "isFemale"
df
#   Lett isFemale
# 1    a        1
# 2    b        0
# 3    c        0
# 4    d        0
# 5    e        1
# 6    f        0

【讨论】:

    【解决方案2】:

    您只需创建一个新列并将性别变量转换为数字

    假设您的数据 = 数据,而性别变量 =sex

           data$sex <- as.factor (data$sex) 
           data$isFemale<- as.numeric (data$sex) 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-03
      • 1970-01-01
      相关资源
      最近更新 更多