0

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!

8
  • What kind of output are you looking for? Commented Jul 9, 2014 at 10:31
  • Why are you using row 2 and row 4 in your example? Commented Jul 9, 2014 at 10:32
  • yes in my example it's row 2 and 4 Commented Jul 9, 2014 at 10:33
  • Does it make any sense? Commented Jul 9, 2014 at 10:34
  • @AnandaMahto, i'm lookink for a new column in my data frame where i can see the result of the function for each row Commented Jul 9, 2014 at 10:34

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.