title: Can I use dplyr mutate() or ifelse statements to make a conditional time since diagnosis variable?
body: <p>I would like to create a "time since diagnosis" variable that is conditional on two other existing variables in my data.    </p>
  
  <p>Here is some example data: </p>
  
  <pre><code>id &lt;- c("0001", "0001", "0001", "0002", "0002", "0002", "0003", "0003", "0003", "0003")
  dementia &lt;- c(0, 0, 1, 0, 1, 1, 0, 1, 0, 1)
  age_visit &lt;- c("80", "81", "82","50", "51", "52","60", "61", "62", "63")
  ds &lt;- data.frame(id, dementia, age_visit)
  </code></pre>
  
  <p>I have a binary diagnosis variable <code>dementia</code> in a long format data set.<br>
  Looks like this:</p>
  
  <pre><code>    id     dementia   age_visit
  1 0001        0        80
  2 0001        0        81
  3 0001        1        82
  4 0002        0        50
  5 0002        1        51
  6 0002        1        52
  7 0003        0        60
  8 0003        1        61
  9 0003        0        62
  </code></pre>
  
  <p>I want an <code>age_at_diagnosis</code> variable that pastes the <code>age_visit</code> for the first instance of the dementia diagnosis, when it first equals 1. This step isn't vital if there is a way to simply skip to the last step which is the time since the first instance of diagnosis. The main problem is that individuals can be diagnosed then have another assessment that is null. I want the first case and then the time since that first assessment to be the time since diagnosis.</p>
  
  <p>So the end result would look like this, with <code>time_sincedx</code> being <code>age_visit - age_at_dx</code>:</p>
  
  <pre><code>     id   dementia    age_visit   age_at_dx    time_sincedx
  1  0001        0        80        NA           NA
  2  0001        0        81        NA           NA
  3  0001        1        82        82            0
  4  0002        0        50        NA           NA
  5  0002        1        51        51            0
  6  0002        1        52        51            1
  7  0003        0        60        NA           NA
  8  0003        1        61        61            0
  9  0003        0        62        61            1
  10 0003        1        63        61            2
  </code></pre>
  
  <p>Is there any way to do this with dplyr?
  I've tried this but it's not quite right. It pastes each age at each occasion leaving me with zero's down the <code>time_since_dx</code> column.</p>
  
  <pre><code>df &lt;- mutate(df, age_at_dx = ifelse(dementia==1, age_at_visit, NA))
  df$time_sincedx&lt;- df$age_at_visit - df$age_atdx
  </code></pre>
  
  <p>Any ideas much appreciated!</p>