0

I have a data set with about 15 000 rows and ten columns. I want to create a new column " difrence" by using columns " ID" and "DATE" in my data set. The "ID" includes the identity number of people the ids are repetitive. How can I create a new column the for each person, and compute the difference of time?

How can I code by R

sara
  • 21
  • 2
  • Welcome to SO, sara. Please include a [minimal reproducible example](https://stackoverflow.com/a/5963610/9462095) e.g. `dput(head(dat))` and a desired output. – Andre Wildberg Jul 12 '23 at 18:09
  • With dplyr: `dat %>% group_by(ID) %>% mutate(newcol = c(NA, diff(DATE)))`. Base R: `dat$newcol <- ave(as.numeric(dat$DATE), dat$ID, FUN = function(z) c(NA, diff(z)))`. – r2evans Jul 12 '23 at 18:14
  • Welcome to SO, sara! Questions on SO (especially in R) do much better if they are reproducible and self-contained. By that I mean including attempted code (please be explicit about non-base packages), sample representative data (perhaps via `dput(head(x))` or building data programmatically (e.g., `data.frame(...)`), possibly stochastically), perhaps actual output (with verbatim errors/warnings) versus intended output. Refs: https://stackoverflow.com/q/5963269, [mcve], and https://stackoverflow.com/tags/r/info. – r2evans Jul 12 '23 at 18:14

1 Answers1

0

You can do something like this:

library(tidyverse)

# create toy dataset
df <- tibble(
    ID = rep(1:5, each = 2),
    Date = seq(as.Date('2023/01/01'), as.Date('2023/10/01'), by="month"))

# I'm assuming you have two Dates for each ID
df %>%
    group_by(ID) %>%
    mutate(
        Difference = diff(Date)) %>%
    ungroup()

# A tibble: 10 × 3
      ID Date       Difference
   <int> <date>     <drtn>    
 1     1 2023-01-01 31 days   
 2     1 2023-02-01 31 days   
 3     2 2023-03-01 31 days   
 4     2 2023-04-01 31 days   
 5     3 2023-05-01 31 days   
 6     3 2023-06-01 31 days   
 7     4 2023-07-01 31 days   
 8     4 2023-08-01 31 days   
 9     5 2023-09-01 30 days   
10     5 2023-10-01 30 days   
Mark
  • 7,785
  • 2
  • 14
  • 34