Reputation: 1706
I have a data frame with three column. I want to apply a function to compare the second and third column, my function will create a new column. With an example :
vin <- c("vin1", "vin2", "vin3", "vin4")
date.fin.obs <- rep(as.Date("2014-07-04"), length(vin))
date.fin <- c(as.Date("2014-07-04"), as.Date("2013-03-21"), as.Date("2013-07-06"),
as.Date("2014-07-04"))
df <- data.frame(vin, date.fin.obs, date.fin)
CumulSurvivants <- function(x, y){
# y <- length(x)
x.num <- as.numeric(x)
y.num <- as.numeric(y)
# i <- length(x)
i <- 0
if(x.num == y.num){
return(i)
}else{
return(i+1)
}
}
CumulSurvivants(x = df$date.fin[2], y = df$date.fin.obs[4])
seems to work, but I want to compare the two column row by row, and to write the result of my function in a new column.
Thanks in advance!
Upvotes: 0
Views: 327
Reputation: 594
To compute the date difference, you may simply use
df$difference <- date.fin.obs - date.fin
resulting in
vin date.fin.obs date.fin difference
1 vin1 2014-07-04 2014-07-04 0 days
2 vin2 2014-07-04 2013-03-21 470 days
3 vin3 2014-07-04 2013-07-06 363 days
4 vin4 2014-07-04 2014-07-04 0 days
Or, instead of the simple "minus", use any other more specialized date/time function in the same way, possibly with date/time formatting. Also have a look at ?strptime
and http://www.statmethods.net/input/dates.html.
Upvotes: 1