【问题标题】:Converting categorical string to number [duplicate]将分类字符串转换为数字[重复]
【发布时间】:2017-07-21 16:31:56
【问题描述】:

我的数据集是这样的

category number 
male        01
male        02
female      03
male        04
male        05

我的问题是如何将类别列转换为male=1female=2。 我想要 1 代替男性,2 代替女性

【问题讨论】:

  • 从重复的帖子中,(a == "female") + 1 会为你工作。

标签: r


【解决方案1】:
levels(df$category)[c("male","female")] <- c(1,2)

如果你想要一个数字向量:

df$category <- as.numeric(df$category)

这应该可以解决!

【讨论】:

  • 但是,变量 category 将保持为 factor...
  • 也许他想替换因子水平。 OP 没有具体说明他的要求。
【解决方案2】:

让我们从一个可重现的例子开始:

x = data.frame(category = c("male", "male", "female", "male", "male"), 
               number = paste0("0", 1:5))

这将创建一个满足您需求的数字向量:

x$cat_num <- as.numeric(factor(x$category, levels = c("male", "female")))
x
#   category number cat_num
# 1     male     01       1
# 2     male     02       1
# 3   female     03       2
# 4     male     04       1
# 5     male     05       1

【讨论】:

    猜你喜欢
    • 2019-10-27
    • 2016-09-06
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 2014-11-15
    相关资源
    最近更新 更多