快速操纵R中的日期

问题描述 投票:-1回答:2

我有大约34000个日期向量,我必须改变这一天并移动月份。我试过这个循环并使用mapply函数,但它非常慢。这是我的一个例子:

library(lubridate)
list_dates = replicate(34000,seq(as.Date("2019-03-14"),length.out = 208,by = "months"),simplify = F)
new_day = round(runif(34000,1,30))
new_day[sample(1:34000,10000)] = NA

new_dates = mapply(FUN = function(dates,day_change){
  day(dates) = ifelse(is.na(rep(day_change,length(dates))),day(dates),rep(day_change,length(dates)))
  dates = as.Date(ifelse(is.na(rep(day_change,length(dates))),dates,dates%m-%months(1)),origin = "1970-01-01")
  return(dates)
},dates = list_dates,day_change = as.list(new_day),SIMPLIFY = F)

变量new_dates应该包含原始日期的列表,相应地移动到变量new_day。侧面的功能如下:

  1. 如果new_day与NA不同,它会将日期的日期更改为新的日期
  2. 如果new_day与NA不同,它将把日期的几个月移到后面。

我愿意接受任何可以提高速度的解决方案,无论使用什么包(如果它们都在CRAN中)。

编辑

因此,根据评论,我减少了2个日期向量列表的示例,每个日期包含2个日期,并创建了新日期的手动向量:

list_dates = replicate(2,seq(as.Date("2019-03-14"),length.out = 2,by = "months"),simplify = F)

new_day = c(9,NA)

这是原始输入(变量list_dates):

[[1]]
[1] "2019-03-14" "2019-04-14"

[[2]]
[1] "2019-03-14" "2019-04-14"

并且mapply函数的预期输出是:

[[1]]
[1] "2019-02-09" "2019-03-09"

[[2]]
[1] "2019-03-14" "2019-04-14"

如您所见,第一个日期向量更改为第9天,每个日期滞后一个月。第二个日期向量没有改变,因为new_dates是该值的NA

r lubridate
2个回答
0
投票

这是一个lubridate解决方案

library(lubridate)
mapply(
    function(x, y) { if (!is.na(y)) {
            day(x) <- y;
            month(x) <- month(x) - 1
        }
        return(x) },
    list_dates, new_day, SIMPLIFY = F)
#[[1]]
#[1] "2019-02-09" "2019-03-09"
#
#[[2]]
#[1] "2019-03-14" "2019-04-14"

或者使用purrr

library(purrr)
library(lubridate)
map2(list_dates, new_day, function(x, y) {
    if (!is.na(y)) {
        day(x) <- y
        month(x) <- month(x) - 1
    }
    x })

0
投票

除了Maurits的解决方案,如果你想进一步提高计算速度,你可能要考虑使用doParallel多核

library(data.table)
library(doParallel)

registerDoParallel(3)
df <- data.table(new_day,list_dates)

mlply(df,
      function(new_day,list_dates){

        list_dates <- list_dates[[1]]

        if(!is.na(new_day)){
          day(list_dates) <- new_day
          list_dates <-  list_dates %m-% months(1)
        }

        return(list_dates)
      }, .parallel = T, .paropts = list(.packages='lubridate')
)
© www.soinside.com 2019 - 2024. All rights reserved.