stevenjoe
stevenjoe

Reputation: 339

Add Months to Date in R (if Data Exists)

I'm having some issues adding months to a date in R, specifically I have a column "Date" that may or may not have a date and another column "Months" that may or may not have a positive integer. If there is both a date and integer I want to add them, something like this:

library(lubridate)
df$End <- ifelse(is.na(df$Start) | is.na(df$Months),"",df$Start %m+% months(ol$Months))

The error I keep getting is as follows:

Error in NextMethod(.Generic) : 
  NAs are not allowed in subscripted assignments

Any ideas? Thanks for your help.

Upvotes: 0

Views: 1612

Answers (1)

Yuval Spiegler
Yuval Spiegler

Reputation: 373

So there is some problem using the %m+% with NA data (even with the ifelse construct). A way around it is to do it with adding days, but different months have different days. So you could subset the data.frame beforehand and then rbind it:

#create a simple data.frame with only one row good row [3,]
date_col <- as.Date(c("2016-04-15", NA, "2015-02-02"))
month_col <- as.numeric(c(NA, NA, 3))                   
df <- data.frame(date_col, month_col)
df
       Start Months
1 2016-04-15     NA
2       <NA>     NA
3 2015-02-02      3

#create new column and divide the data frame into two
df$End <- NA
df1 <- df[!is.na(df$Start) & !is.na(df$Months),]
df2 <- df[is.na(df$Start) | is.na(df$Months),]

#add months to End column
df1$End <- df1$Start %m+% months(df1$Months)

#and in the darkness bind them
df <- rbind(df1, df2)
> df
        Start Months        End
3  2015-02-02      3 2015-05-02
2  2016-04-15     NA       <NA>
31       <NA>     NA       <NA>

Upvotes: 1

Related Questions