【问题标题】:Create sequence of dates in R with pipe %>%使用管道 %>% 在 R 中创建日期序列
【发布时间】:2022-01-12 22:20:11
【问题描述】:

我正在尝试从原始字符串创建日期序列。

library(tidyverse)
tmp <- "1900-01-01 3000-01-01"

这会产生一个长度为 2 的向量:

tmp %>% str_split(., " ", simplify = T) %>% as.vector() %>% as.Date

我需要根据该管道的结果创建一系列日期。我的工作流程需要使用管道运算符。

tmp %>% str_split(., " ", simplify = T) %>% as.vector() %>% as.Date %>% seq(from = magrittr::extract(., 1), to = magrittr::extract(., 2), by = "1 day")

这个实现失败了,我不确定为什么。但我也试过这个,但无济于事:

tmp %>% str_split(., " ", simplify = T) %>% as.vector() %>% as.Date %>% magrittr::extract(., 1):magrittr::extract(., 2)

seq() 不支持管道吗?我错过了什么?

【问题讨论】:

    标签: r tidyverse


    【解决方案1】:

    您可以使用fread 将文本读取为包含两列的以空格分隔的文件。

    在 CRAN 版本的 data.table 中,您必须使用 tz = 'UTC' 来让它解析日期。在不需要的开发版本中。

    tmp <- "1900-01-01 3000-01-01"
    library(data.table)
    
    fread(text = tmp, tz = 'UTC')[, seq(V1, V2, by = '1 day')]
    #>     [1] "1900-01-01" "1900-01-02" "1900-01-03" "1900-01-04" "1900-01-05"
    #>     [6] "1900-01-06" "1900-01-07" "1900-01-08" "1900-01-09" "1900-01-10"
    #>    [11] "1900-01-11" "1900-01-12" "1900-01-13" "1900-01-14" "1900-01-15"
    #>    [ reached 'max' / getOption("max.print") ]
    

    reprex package 创建于 2021-12-07 (v2.0.1)

    或类似于@akrun 的回答:

    library(rlang)
    library(stringr)
    
    tmp %>% 
      str_split(" ", simplify = TRUE) %>%
      as.Date %>% 
      exec(seq, !!!., by = '1 day')
    

    【讨论】:

    • 为了咯咯笑,基础管道实现 - strsplit(tmp, " ")[[1]] |&gt; as.Date() |&gt; (\(x) seq(x[1], x[2], by="1 day"))()
    【解决方案2】:

    我们可以用{}阻止

    library(stringr)
    library(dplyr)
    tmp %>% 
       str_split(., " ", simplify = TRUE) %>%
       as.vector() %>% 
       as.Date %>% 
       {seq(from = magrittr::extract(., 1), 
         to = magrittr::extract(., 2), by = "1 day")}
    

    【讨论】:

    • as.vector 似乎也没有必要。
    • @thelatemail 是的,你是对的。我只更改了 OP 有问题的部分。
    • 可以确认,as.vector() 是多余的。 simplify = T 返回一个矩阵,可以直接通过管道传递给as.Date。感谢您指出这一点。
    【解决方案3】:

    第一个使用 magrittr %$%,第二个仅使用 %>%,第三个仅使用带有基本 R 管道的基本 R,第四个与第一个绑定为最短,仅使用没有管道的基本 R .

    library(magrittr)
    
    tmp %>% read.table(text = ., colClasses = "Date") %$% seq(V1, V2, 1)
    
    tmp %>% read.table(text = ., colClasses = "Date") %>% with(seq(V1, V2, 1))
    
    tmp |>
      textConnection() |>
      read.table(colClasses = "Date") |>
      with(seq(V1, V2, 1))
    
    with(read.table(text = tmp, colClasses = "Date", seq(V1, V2, "day"))
    

    注意

    tmp <- "1900-01-01 1900-01-04"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-02
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 2023-03-18
      • 2015-08-19
      • 1970-01-01
      • 2015-10-30
      相关资源
      最近更新 更多