【问题标题】:Coding string to numeric in R在R中将字符串编码为数字
【发布时间】:2012-08-21 22:45:00
【问题描述】:

我在 R 中有一个数据集,其中有一列包含 0-1 个月、8-9 个月等。我想将此列编码为带有月数的数字变量。例如,而不是 8-9 个月,只放 9。 感谢您的帮助和cmets。

【问题讨论】:

  • 还可以查看类似问题的答案here

标签: r statistics


【解决方案1】:

一气呵成

a <- c("0-1 month", "8-9 months")
as.integer(gsub("^[[:digit:]]+-([[:digit:]]+) month[s]*", "\\1", a))

【讨论】:

  • 我编辑了输入,因为它试图将“0-1”和“8-9”转换为整数。
  • 如果字符串中没有“month(s)”,则可以去掉我给出的行中的`month[s]*`部分。
【解决方案2】:

使用 car 包中的 recode 函数。它不像gsub 解决方案那样简洁,但更灵活,可能更易于阅读:

library(car)
a <- c("0-1 month", "8-9 months")
recode(a, '"0-1 month" = 1; "8-9 months" = 2')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-28
    • 2014-02-26
    • 2012-10-27
    • 1970-01-01
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多