lundi 24 août 2015

Using ifelse and as.yearmon together

I have some issues using an 'ifelse' statement together with 'as.yearmon' from the zoo package.

My initial dataset is similar to 'df'. From it, I'd like to calculate the duration of each row. So first, I created a column with the start date ('initdate') and then another column with the end date ('enddate'), which must correspond to the suspension date if there is any, or to the current date if there is none.

Here is my code:

require(data.table)
require(zoo)

df <- data.table(id=c(1:3), month1=c(3,2,5), year1=c(2011,2012,2014), monthsusp=c(2,NA,NA), yearsusp=c(2012,NA,NA), weight=c(1,1,1))

#Add column with concatenated 'month year'
df$initdate <- as.yearmon(paste(df$month1,df$year1, sep = "-"),"%m-%Y")

#Create 'current date’
date <- Sys.Date()  #to get current system's date
x <- format(date,"%m")
y <- format(date,"%Y")
df$curmonth <- x
df$curyear <- y

#Add column with current date OR suspension date if any
df <- transform(df, enddate = ifelse(yearsusp > 1, monthsusp, as.yearmon(paste(df$curmonth,df$curyear, sep = "-"),"%m-%Y")))

I only get NAs when there is no suspension date... I don't understand why. Can you help, pretty please? Note that I'm very new to R, which is why my coding might be a little awkward (especially the 'create current date' section) :)

Cheers,

Fred

Aucun commentaire:

Enregistrer un commentaire