【问题标题】:Parsing custom Dates and Months in Roman Numerals with Tidyverse? [duplicate]使用 Tidyverse 解析罗马数字中的自定义日期和月份? [复制]
【发布时间】:2018-02-22 03:17:50
【问题描述】:

Tidyverse 有很棒的 Readr,它有各种各样的解析命令,例如 parse_dateparse_*parse_factorguess_parser。我有一个自定义的month-year 格式,就罗马数字而言,如下所示

> emptyOffices$Month
[1] " II/90" " I/91"  " II/91" " I/92"  " II/92" " I/93"  " II/93"

> guess_parser(emptyOffices$Month)
[1] "character"

I 代表一月,II 代表二月,所以没有。例如,II/90 代表 February 1990guess_parser猜错了月份年份的意思。也许,有一个工具可以让我定义月份来帮助解析器理解这一点?

在一些 Tidyverse 包中是否存在一些工具来读取自定义日期,如罗马数字?

【问题讨论】:

    标签: r date parsing tidyverse readr


    【解决方案1】:

    必须有更好的整洁解决方案,但这个可行:

    library(dplyr)
    foo <- c("II/90", "I/91", "II/91", "I/92", "II/92", "I/93", "II/93")    
    foo %>%
        tibble() %>%
        mutate(year     = gsub(".*/", "", .), 
               monthRom = as.roman(gsub("/.*", "", .))) %>%
        mutate(monthNum = as.numeric(monthRom)) %>%
        mutate(monthChr = month.abb[monthNum])
    # A tibble: 7 x 5
          .  year monthRom monthNum monthChr
      <chr> <chr>    <chr>    <dbl>    <chr>
    1 II/90    90       II        2      Feb
    2  I/91    91        I        1      Jan
    3 II/91    91       II        2      Feb
    4  I/92    92        I        1      Jan
    5 II/92    92       II        2      Feb
    6  I/93    93        I        1      Jan
    7 II/93    93       II        2      Feb
    

    或者你可以简单地这样做:

    foo %>%
        gsub("/.*", "", .) %>%
        as.roman() %>%
        as.numeric() %>%
        month.abb[.]
    

    使用as.roman from utils将对象转换为roman类,将此对象转换为数字字符串并从basemonth.abb中提取月份。

    【讨论】:

      猜你喜欢
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多