29

Rの現在の日付から前月の開始日と終了日を取得する簡単な方法はありますか?

私は現在の日付しか持っていません。そこから、前月、前月の開始日、前月の終了日を取得したい。

currentDate<-Sys.Date() #return today's date as "2012-11-07"

今日の日付から前月の開始日を2012-10-01、終了日を2012-10-31にします。

4

7 に答える 7

38

多くのパッケージには便利な日付機能がありますが、独自の機能を使用するには、次のようにします。

月の始まり関数:

som <- function(x) {
  as.Date(format(x, "%Y-%m-01"))
}

および月末関数(ただし、ここではこれは必要ありません):

eom <- function(x) {
  som(som(x) + 35) - 1
}

それはあなたを動かすはずです。たとえば、前月末を取得するには、次のようにします。

som(Sys.Date()) - 1
[1] "2012-10-31"

と月の初め:

som(som(Sys.Date()) - 1)
[1] "2012-10-01"
于 2012-11-07T11:27:28.593 に答える
30

それを使用lubridateするのは簡単です:

library(lubridate)
floor_date(Sys.Date() - months(1), "month")

Rには優れたライブラリがたくさんあります。必要なものはすべてすでに作成されているようです。

更新版:

library(lubridate)
floor_date(as.Date("2011-03-29"), "month") - months(1)

これは、3月29日にうまく機能するように修正されています。

于 2015-04-07T06:53:04.513 に答える
18

lubridate日付演算に非常に優れたライブラリを使用できます。

library(lubridate)

currentDate <-Sys.Date()
# end of previous month:
eopm <- currentDate - days(day(currentDate))
# [1] "2012-10-31"

# start of previous month:
sopm <- currentDate - days(day(currentDate))
sopm <- sopm - days(day(sopm) - 1)
# [1] "2012-10-01"
于 2012-11-07T15:17:17.463 に答える
16

lubridateパッケージのもう1つのオプションは、ロールバック関数を使用することです。これは、説明にあるように、まさにそれを実行します。

ロールバックにより、日付が前月の最終日または月の初日に変更されます。オプションで、新しい日付は同じ時間、分、秒の情報を保持できます。

library(lubridate)

currentDate <- Sys.Date()

end_last_month <- rollback(currentDate)

init_last_month <- rollback(end_last_month, roll_to_first = TRUE)
于 2016-03-29T18:51:20.290 に答える
3

前月の開始日:

format(Sys.Date() - 30, '%Y-%m-01')

前月の終了日:

as.Date(format(Sys.Date(), '%Y-%m-01')) - 1
于 2016-11-06T21:32:22.147 に答える
1

timeperiodsR任意の期間の開始日と終了日を取得するために使用します。

# install.packages("timeperiodsR")
timeperiodsR::previous_month()
于 2019-10-03T08:38:02.937 に答える
0

このソリューションは、「2022-03-01」から30日を引くと、2月ではなく1月に到着するという事実を考慮に入れています。

# Get end date of previous month
end <- (as.Date(format(Sys.Date(), "%Y-%m-01")) - 1) 

# Get start date of previous month after knowing end date
start <- as.Date(format(end, "%Y-%m-01")) 

start
#> [1] "2022-02-01"
end
#> [1] "2022-02-28"

# Works in edge cases where subtracting 30 days 
# from the current datewill not give you the previous month
date <- "2022-03-01"
end <- (as.Date(format(date, "%Y-%m-01")) - 1) 
#> Error in format.default(date, "%Y-%m-01"): invalid 'trim' argument

# Get start date of previous month after knowing end date
start <- as.Date(format(end, "%Y-%m-01")) 

start 
#> [1] "2022-02-01"
end
#> [1] "2022-02-28"

reprexパッケージ(v2.0.1)によって2022-03-04に作成されました

これは、可変期間(日、週、月、年)とすべてをベースRで使用して、より柔軟な方法でこれを解決するために作成した関数です。

calc_previous_date_range <- function(x,
                                     time_period = c("day", "week", "month", "year"),
                                     multiplier = 1,
                                     is_complete = TRUE,
                                     week_start = 1) {
  
  time_period <- match.arg(time_period)
  
  if (multiplier == 0) stop(call. = FALSE, "`multiplier` cannot equal 0")
  
  if (time_period == "day") {
    
    if (is_complete) {
      
      start <- x - multiplier
      
      end <- Sys.Date() - 1
      
    } else {
      
      start <- x - (multiplier - 1)
      
      end <- x
      
    }
    
  } else if (time_period == "week") {
    
    if (is_complete) {
      
      start <- cut(x - (7 * multiplier), breaks = 'week', start.on.monday = week_start) 
      start <- as.Date(start)
      
      end <- cut(x, breaks = "week", start.on.monday = week_start) 
      end <- as.Date(end)
      
      end <- end - 1
      
    } else {
      
      start <- cut(x, breaks = 'week', start.on.monday = week_start) 
      
      if (multiplier > 0) {
        start <- as.Date(start) - (7 * (multiplier - 1)) 
      }
      
      end <- x
      
    }
    
  } else if (time_period == "month") {
    
    if (is_complete) {
      
      end <- as.Date(format(x, "%Y-%m-01")) - 1
      
      start <- as.Date(format(as.Date(end), "%Y-%m-01"))
      
      if (multiplier > 1) {
        
        old_month <- as.numeric(format(start, "%m"))
        
        old_year <- as.numeric(format(start, "%Y"))
        
        # Calc new month
        new_month <- format(seq(start, length = multiplier, by = "-1 months")[multiplier], "%m")
        
        # Calc new year
        if (multiplier >= old_month) {
          
          new_year <- old_year - (1 + floor(((multiplier - old_month) / 12)))
          
        } else {
          
          new_year <- old_year
          
        }
        
        start <- as.Date(paste0(new_year, "-", new_month, "-01")) 
        
      }
      
    } else {
      
      start <- format(x, "%Y-%m-01")
      
      start <- as.Date(start)
      
      if (multiplier > 1) {
        
        old_month <- as.numeric(format(start, "%m"))
        
        old_year <- as.numeric(format(start, "%Y"))
        
        # Calc new month
        new_month <- format(seq(start, length = multiplier, by = "-1 months")[multiplier], "%m")
        
        # Calc new year
        if (multiplier >= old_month) {
          
          new_year <- old_year - (1 + floor(((multiplier - old_month) / 12)))
          
        } else {
          
          new_year <- old_year
          
        }
        
        start <- as.Date(paste0(new_year, "-", new_month, "-01")) 
        
      }
      
      end <- x
      
    }
    
  } else if (time_period == "year") {
    
    if (is_complete) {
      
      end <- as.Date(format(x, "%Y-01-01")) - 1
      
      start <- as.Date(format(as.Date(end), paste0(as.numeric(format(end, "%Y")) - (multiplier - 1), "-01-01"))) 
      
    } else {
      
      start <- format(x, "%Y-%m-01") 
      
      start <- as.Date(start)
      
      if (multiplier > 1) {
        
        old_year <- as.numeric(format(as.Date(start)))
        
        start <- format(start, old_year - (multiplier - 1), "-%m-01") 
        
        start <- as.Date(start)
        
      }
      
      end <- x
      
    }
    
  }
  
  c(start, end)
  
}

いくつかの例:

# Last 6 days (including partial days, i.e. today)
calc_previous_date_range(Sys.Date(), "day", 6, is_complete = FALSE)
#> [1] "2022-02-27" "2022-03-04"

# Last complete 6 days 
calc_previous_date_range(Sys.Date(), "day", 6, is_complete = TRUE)
#> [1] "2022-02-26" "2022-03-03"

# Last 3 weeks (including current week)
calc_previous_date_range(Sys.Date(), "week", 3, is_complete = FALSE)
#> [1] "2022-02-14" "2022-03-04"

# Last 3 complete weeks
calc_previous_date_range(Sys.Date(), "week", 3, is_complete = TRUE)
#> [1] "2022-02-07" "2022-02-27"

# Last 3 complete weeks where week start is Sunday instead of Monday
calc_previous_date_range(Sys.Date(), "week", 3, is_complete = TRUE, week_start = 0)
#> [1] "2022-02-06" "2022-02-26"

# Last month (including current month)
calc_previous_date_range(Sys.Date(), "month", 1, is_complete = FALSE)
#> [1] "2022-03-01" "2022-03-04"

# Last complete month
calc_previous_date_range(Sys.Date(), "month", 1, is_complete = TRUE)
#> [1] "2022-02-01" "2022-02-28"

# Last 6 complete months
# Note that the year is handled properly 
calc_previous_date_range(Sys.Date(), "month", 6, is_complete = TRUE)
#> [1] "2021-09-01" "2022-02-28"

# Last year (including current year)
calc_previous_date_range(Sys.Date(), "year", 1, is_complete = FALSE)
#> [1] "2022-03-01" "2022-03-04"

# Last year (excluding current year)
calc_previous_date_range(Sys.Date(), "year", 1, is_complete = TRUE)
#> [1] "2021-01-01" "2021-12-31"

# Last 3 years (excluding current year)
calc_previous_date_range(Sys.Date(), "year", 3, is_complete = TRUE)
#> [1] "2019-01-01" "2021-12-31"
于 2022-03-04T17:39:50.110 に答える