Calculate number of days between two dates in r

后端 未结 4 1650
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 23:22

I need to calculate the number of days elapsed between multiple dates in two ways and then output those results to new columns: i) number of days that has elapsed as compare

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-17 23:48

    This will get you what you want:

    d <- as.Date(DATA$DATE, format="%m/%d/%Y")
    
    first <- c()
    for (i in seq_along(d))
        first[i] <- d[i] - d[1]
    
    between <- c(0, diff(d))
    

    This uses the as.Date() function in the base package to cast the vector of string dates to date values using the given format. Since you have dates as month/day/year, you specify format="%m/%d/%Y" to make sure it's interpreted correctly.

    diff() is the lagged difference. Since it's lagged, it doesn't include the difference between element 1 and itself, so you can concatenate a 0.

    Differences between Date objects are given in days by default.

    Then constructing the output dataframe is simple:

    RESULTS <- data.frame(DATE=DATA$DATE, FIRST=first, BETWEEN=between)
    

提交回复
热议问题