New variable - date

I am working with a dataset that includes 150 individuals that each have 1-7 bloodsamples registered. Each blood sample is listed as a line, meaning that an ID will appear in multiple lines, if this person has multiple samples.

I need to make a new variable telling me the date of the first blood sample for each individual. Any suggestions? I have attached a picture to illustrate my point.

Thank you very much.

The following should do what you're hoping for:

library(tidyverse)
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union


samples <- tribble(
  ~id, ~blood_sample,
  1, "01.01.2010",
  1, "04.02.2012",
  1, "05.02.2013",
  1, "06.08.2014",
  1, "08.10.2018",
  2, "04.07.2015",
  2, "03.06.2018",
  3, "12.12.2012",
  3, "11.05.2015",
  3, "05.11.2018"
)

samples %>%
  mutate(blood_sample = mdy(blood_sample)) %>%
  group_by(id) %>%
  arrange(blood_sample) %>%
  mutate(first_sample = first(blood_sample)) %>%
  ungroup() %>%
  arrange(id)
#> # A tibble: 10 x 3
#>       id blood_sample first_sample
#>    <dbl> <date>       <date>      
#>  1     1 2010-01-01   2010-01-01  
#>  2     1 2012-04-02   2010-01-01  
#>  3     1 2013-05-02   2010-01-01  
#>  4     1 2014-06-08   2010-01-01  
#>  5     1 2018-08-10   2010-01-01  
#>  6     2 2015-04-07   2015-04-07  
#>  7     2 2018-03-06   2015-04-07  
#>  8     3 2012-12-12   2012-12-12  
#>  9     3 2015-11-05   2012-12-12  
#> 10     3 2018-05-11   2012-12-12

Created on 2021-08-02 by the reprex package (v2.0.0)

Thank you! Unfortunately I can't get it to run.. Maybe I'm putting my dataset in wrong..

I should add, that I want to add this vale as a column in an existing dataset.

Let's assume I have a dataset called Bloodsample_overview, that holds all my values - how would you put this in?

If I understand correctly then you would just replace samples with Bloodsample_overview and make sure the column names match what you have in your dataset. If you provide a reprex that could help determine the problem.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.