相关疑难解决方法(0)

如何从R中的日期减去月份?

我试图从日期中减去n个月,如下所示:

maturity <- as.Date("2012/12/31")

m <- as.POSIXlt(maturity)

m$mon <- m$mon - 6
Run Code Online (Sandbox Code Playgroud)

但结果日期是01-Jul-2012,而不是30-Jun-2012我所期望的.有没有简短的方法来获得这样的结果?

提前致谢

r

36
推荐指数
3
解决办法
5万
查看次数

在posix时间添加一年

我有一个像"2016-01-01"(YYYY-MM-DD)的日期,我正在as.numeric(as.POSIXct(...))使用它作为整数.

我的问题是,有没有办法在一年,一个月或一天中添加到这个日期?我的意思是,如果我在2016年增加一年,它将与2015年增加一年(bissextile stuff)相同.

与在1月1日添加32天相同,与在2月01日添加32天相同(因为可能更改的天数)

我设法把东西了年和月的作品,但我想实现以及

how_long_is_simul <- function(lst){
    # Format DATE_START
    greg_date = intDate_to_gregorianDate(DATE_START)
    reg = "^([0-9]{4})\\-([0-9]{2})\\-([0-9]{2})$" # black-magic
    splited_date = str_match(greg_date, reg)

    # Manage months limit
    lst$years = lst$years + floor(lst$months/12)
    lst$months = lst$months%%12

    # Build new date
    my_vector = c(lst$years, lst$months, 0)
    end_date = paste(as.numeric(splited_date[2:4]) + my_vector, collapse = "-")
    return(round((gregorianDate_to_intDate(end_date)-DATE_START)/86400))
}

# AND the vars used by the function
DATE_START <- 1451606400 # 2016-01-01 GMT
lst   = list( # no days, …
Run Code Online (Sandbox Code Playgroud)

r date posixct

7
推荐指数
1
解决办法
6580
查看次数

根据其他变量的函数创建新变量

如何将列entires作为参数传递给函数,然后创建一个新列,它是另外两个函数的函数?例如,利用这个优秀的功能将月份添加到日期,并采用此示例数据框:

df <- structure(
  list(
date = structure(
  c(
    17135,
    17105,
    17105,
    17074,
    17286,
    17317,
    17317,
    17347,
    17105,
    17317
  ),
  class = "Date"
),
monthslater = c(10,
                11, 13, 14, 3, 3, 3, 3, 4, NA)
  ),
  .Names = c("date", "monthslater"),
  row.names = c(NA, 10L),
  class = "data.frame"
)
Run Code Online (Sandbox Code Playgroud)

我想创建一个新的列,我通过从列项date,并monthslater 以功能add.months我本来以为像这样的工作:

df$newdate <- add.months(df$date, df$monthslater)
Run Code Online (Sandbox Code Playgroud)

但事实并非如此.

该函数的完整代码是:

add.months <- function(date,n) seq(date, by = paste(n, "months"), length = 2)[2]
Run Code Online (Sandbox Code Playgroud)

r date function dataframe

4
推荐指数
1
解决办法
80
查看次数

在 R 中将日期偏移一个月

我有个约会,比方说 2020 年 7 月 7 日。

my_date <- as.Date("2020/07/07")
Run Code Online (Sandbox Code Playgroud)

我想将这个日期抵消一个月。所以它应该在 2020 年 8 月 7 日返回。

我试过,my_date + 30但如果一个月有 30 或 31 天,它就不起作用。

编辑

我的问题必须准确。如果日期是 2020 年 5 月 31 日怎么办?它应该抵消到 2020 年 6 月 30 日。请在 R 基础上提供帮助。

任何帮助将不胜感激。

r

2
推荐指数
1
解决办法
115
查看次数

标签 统计

r ×4

date ×2

dataframe ×1

function ×1

posixct ×1