简体   繁体   English

使用用户定义的函数处理向量中的NA

[英]Dealing with NAs in vectors with user-defined functions

I'm trying to create a function in R that replicates Excel's EOMonth function (ie you enter a date and a number of months and it returns you the end of the month date for the same number of months before / after the input date). 我正在尝试在R中创建一个复制Excel的EOMonth函数的函数(即,您输入一个日期和一个月数,并返回与输入日期之前/之后相同的月数的月底日期)。 I've a got a function that works on a single input using the lubridate package: 我有一个使用lubridate包在单个输入上工作的函数:

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

The problem is how to 'vectorise' this (not sure that's the right word). 问题是如何将其“向量化”(不确定这是正确的词)。 When I pass the function a vector (in this case a column in a data frame), I get the following message: 当我向函数传递向量时(在这种情况下为数据帧中的列),我得到以下消息:

NAs are not allowed in subscripted assignments 下标作业中不允许使用NA

I don't want to ignore any NAs in the vector (because I am sending the results to a new column in the data frame). 我不想忽略向量中的任何NA(因为我将结果发送到数据帧中的新列)。 I just want the function, when it sees an NA, to return an NA, but to process all the valid dates as the function dictates. 我只希望函数在看到不适用项时返回不适用项,但要按功能指示处理所有有效日期。 I'm really confused as to how to do this; 我对如何做到这一点感到很困惑。 most of the posts I have seen on this topic relate to how to ignore / remove NAs from the results. 我在该主题上看到的大多数帖子都与如何忽略/删除结果中的NA无关。

Any help would be greatly appreciated. 任何帮助将不胜感激。

Thanks. 谢谢。

Edit. 编辑。 Added in some sample data. 添加了一些示例数据。 Below is 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 the following: 因此,输入以下内容:

newVector <- EOMonth(OldVector, 3)

Should return the end of the month for each of the dates in 3 months' time: 应该在3个月的时间内返回每个日期的月末:

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 is to first make a vector of NAs and then process only the non-NA elements of date . 一种解决方案是首先创建NA的向量,然后仅处理date的非NA元素。 Note the NA class needs to be date or the dates are converted to numeric. 请注意,NA类必须为date或者日期将转换为数字。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM