Home > Enterprise >  R Lubridate pass a data table column value as the argument to month parameter instead of fixed integ
R Lubridate pass a data table column value as the argument to month parameter instead of fixed integ

Time:05-12

I have a data table with two columns: a date column and another column with an integer value. I'd like to use the value in the integer column as the number of months to add to the date column. I have a feeling this may require something like apply [or lapply] to traverse the rows instead since passing a datatable column is not technically a scalar input value but rather a vector of multiple scalars. Any quick thoughts on how to achieve this?

works in my dataset

 dateTableProdKeep$"PROD_month"  <- dateTableProdKeep$"calc_new_date" %m % months(1)

does not work when trying to pass a datatable column to the months argument

 dateTableProdKeep$"PROD_month"  <- dateTableProdKeep$"calc_new_date" %m % months(dataTableProdKeep$"Month")

Here's a sample where passing 1 as argument to months works. I'd like that value to come from the Month column.

    library(lubridate)
    #library(tibble)
    
    calc_new_date <- c( "1/1/2022" , "1/31/2022" )
    Month <- c( 3 , 1 )
    
    dateTableProdKeep <- data.frame( calc_new_date , Month )
    
    dateTableProdKeep$"calc_new_date" <- as.Date( dateTableProdKeep$"calc_new_date" , format="%m/%d/%Y" )
    dateTableProdKeep
    
    dateTableProdKeep$"PROD_month" <- dateTableProdKeep$"calc_new_date" %m % months(1)
    dateTableProdKeep

    dateTableProdKeep
      calc_new_date Month PROD_month
    1      1/1/2022     3 2022-01-01
    2     1/31/2022     1 2022-01-31

UPDATE code with solution example adapted from @MartinGal and applied to my original question:

    library(lubridate)
    #library(tibble)
    
    calc_new_date <- c( "1/1/2022" , "1/31/2022" )
    Month <- c( 3 , 1 )
    
    dateTableProdKeep <- data.frame( calc_new_date , Month )
    
    dateTableProdKeep$"calc_new_date" <- as.Date( dateTableProdKeep$"calc_new_date" , format="%m/%d/%Y" )
    dateTableProdKeep
    
    #dateTableProdKeep$"PROD_month" <- dateTableProdKeep$"calc_new_date" %m % months(1)
    dateTableProdKeep
    
    
    
    #tibble(x = 1:100,date = seq(as.Date("2001-01-31"),by = "months", length = length(x)),z = date %m % months(x))
    
    dateTableProdKeep$"new" <- dateTableProdKeep$"calc_new_date" %m % months(dateTableProdKeep$"Month")
    dateTableProdKeep

calc_new_date Month        new
1    2022-01-01     3 2022-04-01
2    2022-01-31     1 2022-02-28

CodePudding user response:

Is this what you're getting at:

tibble(x = 1:100,date = seq(as.Date("2000-01-01"),by = "months", length = length(x)),z = date %m % months(x))
  • Related