Home > Enterprise >  Difference between date and condition
Difference between date and condition

Time:10-12

I would like to do the difference between the date, also the dataset has a unique code and a condition to respect.

a <-c(1,1,1,2,2,2)
b <-c(  01/01/2021,     02/01/2021,     03/01/2021, 01/01/2021,     02/01/2021,     03/01/2021)
c <- c("AB","AC1","AD","AB","AC2","AD")
data <- rbind(a,b,c)

RESULT

A AD-AC
1 1
2 1

A is the unique code (key) And I need to do AD-AC for each key

I can use difftime for calculate the day but I don't know how to do reiterative.

CodePudding user response:

Use strptime and difftime.

a <- c(1,1,1,2,2,2)
b <- strptime(c("01/01/2021","02/01/2021","03/01/2021",
                "01/01/2021","02/01/2021","03/01/2021"), "%d/%m/%Y")
c <- c("AB","AC1","AD","AB","AC2","AD")

d <- data.frame(a,b,c)                   # data frame for work
r <- c()                                 # vector for result
k <- unique(a)                           # unique code (key) "A" 
for(i in k){
    t <- d[d$a == i, ]                   # target row group
    ad <- t[t$c == "AD", ]$b
    ac <- t[grep("^AC\\d*$", t$c), ]$b   # for AC1, AC2,...
    r <- c(r, as.numeric(difftime(ad, ac, units = "days")))
}
data.frame("A"=k, "AD_AC"=r)

#     A  AD_AC
#  1  1    1
#  2  2    1
  • Related