简体   繁体   English

在R中添加月份到日期(如果存在数据)

[英]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. 我在向R中的日期添加月份时遇到了一些问题,特别是我有一个“日期”列,它可能有或没有日期,而另一列“月”中可能有或没有正整数。 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. 谢谢你的帮助。

So there is some problem using the %m+% with NA data (even with the ifelse construct). 因此,将%m+%与NA数据一起使用(即使使用ifelse构造)也存在一些问题。 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: 所以,你可以事先子集的data.frame然后rbind它:

#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>

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

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