【问题标题】:Convert month names to numbers in r将月份名称转换为 r 中的数字
【发布时间】:2020-01-28 02:47:54
【问题描述】:

我正在使用包含完整月份名称的数据:

months <- c("March",     "April",     "May",       "June",      "July",  "August",  "September")

有没有将它们转换为数字的函数?

非常感谢

【问题讨论】:

    标签: date time recode


    【解决方案1】:

    您可以将match() 与内置变量month.name 一起使用。

    match(months, month.name)
    [1] 3 4 5 6 7 8 9
    

    或者将您的月份变量转换为一个因子,然后是一个整数:

    as.integer(factor(months, levels = month.name))
    

    【讨论】:

      【解决方案2】:

      另一种方法是通过命名向量链接月份编号和名称

      months <- c("March",     "April",     "May",       "June",      "July",  "August",  "September")
      x <- setNames(1:12, month.name)
      unname(x[months] )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-08-07
        • 1970-01-01
        • 2011-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-11
        • 2012-11-26
        相关资源
        最近更新 更多