Adding a column that starts from 0 and produces sequential numbers per individual

Viewed 25

I have a data set with multiple observations per individual, that all cover the same distance i.e. 20 micrometers, each individual has a range of 31 to 35 observations over these 20 micrometers. The main problem that this way, all individuals have different Dist_micm start points. I want to make them all start at 1 or 0, in order to be able to plot all of them together.

df

ID    Dist_micm  Conc
1_29  56.18       3514.919
1_29  56.75       3507.629
.     .            .
1_29  76.01       3495.644
1_29  76.18       3400.644
3_18  105.25      2873.534
3_18  105.83      2879.544
 .     .           .
3_18  125.83      2905.698

I tried binning the Dist_micm column using the following code:

df_bin <- df %>%
group_by(ID) %>%
mutate(Dist_bin=ntile(Dist_micm, n=20))%>%
ungroup()

Which gave me this:

df_bin

ID    Dist_micm   Conc     Dist_bin
1_29  56.18       3514.919  1
1_29  56.75       3507.629  1
.     .            .        .
1_29  76.01       3495.644  19
1_29  76.18       3400.644  20
3_18  105.25      2873.534  1
3_18  105.83      2879.544  1
 .     .           .        .
3_18  124.03      2895.798  19
3_18  125.83      2905.698  20

This is sort of half-way to what I need, because I would prefer if each row had a unique Dist, more similar to the original variable Dist_micm, something like this:

df_desired

ID    Dist_micm   Conc     Dist
1_29  56.18       3514.919  1.18
1_29  56.75       3507.629  1.75
.     .            .        .
1_29  76.01       3495.644  19.01
1_29  76.18       3400.644  20.18
3_18  105.25      2873.534  1.25
3_18  106.03      2879.544  1.63
 .     .           .        .
3_18  124.03      2895.798  19.03
3_18  125.83      2905.698  20.01

I don't really mind what form the numbers in the new Dist column take, as long as they are sequential, per each individual, and start from 0 or 1 and finish at 20, the above is just an example.

Many thanks for any ideas to solve this!

0 Answers
Related