r - Dealing with NAs in vectors with user-defined functions -


i'm trying create function in r replicates excel's eomonth function (i.e. enter date , number of months , returns end of month date same number of months before / after input date). i've got function works on single input using lubridate package:

eomonth <- function(date, months)  {    newdate <- date %m+% months(months)    newdate <- ceiling_date(newdate, "month") - days(1) } 

the problem how 'vectorise' (not sure that's right word). when pass function vector (in case column in data frame), following message:

nas not allowed in subscripted assignments

i don't want ignore nas in vector (because sending results new column in data frame). want function, when sees na, return na, process valid dates function dictates. i'm confused how this; of posts have seen on topic relate how ignore / remove nas results.

any appreciated.

thanks.

edit. added in sample data. below sample input data:

01/07/2016 na 22/07/2016 na 30/06/2016 22/07/2016 22/07/2016 29/07/2016 na 22/07/2016 30/06/2016 na 31/01/2016 02/08/2016 

so, entering following:

newvector <- eomonth(oldvector, 3) 

should return end of month each of dates in 3 months' time:

31/10/2016 na 31/10/2016 na 30/09/2016 31/10/2016 31/10/2016 31/10/2016 na 31/10/2016 30/09/2016 na na 30/04/2016 30/11/2016 

one solution first make vector of nas , process non-na elements of date. note na class needs date or dates converted numeric.

eomonth <- function(date, months)  {   newdate <- date(rep(na, length(date)))   newdate[!is.na(date)] <- date[!is.na(date)] %m+% months(months)    newdate[!is.na(date)] <- ceiling_date(newdate[!is.na(date)], "month") - days(1)   newdate }  eomonth(oldvector, 3) 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -