I am a fairly new user and I need your help with a task that I am stuck on. If my question has been asked/answered before I would be grateful if you could kindly guide me to the relevant page.
I have the following data set (lbnp_br) which is optical density (OD) measured over time (in seconds):
time OD
1891 -244.6
1891.5 -244.4
1892 -242
1892.5 -242
1893 -241.1
1893.5 -242.4
1894 -245.2
1894.5 -249.6
**1895 -253.9**
1895.5 -254.5
1896 -251.9
1896.5 -246.7
1897 -242.4
1897.5 -234.6
1898 -225.5
I need to find out how responsive the study device is by measuring how long it takes to reach the threshold for optical density.
For this I have calculated the coefficient of variation (CV) of OD and I am using mean OD (-252.9098) +/- 2*CV to define a response threshold. For the above data the threshold is set as (mean OD + 2*CV = -252.9917), and (mean OD - 2*CV = -252.8278).
I now need to calculate the time in seconds from the start (1891 seconds) to the first OD value that exceed the +/- threshold values. For example for the above data frame this threshold is exceeded at 1895 seconds corresponding to an OD of -253.9.
I now have to repeat this 3 times for each study subject and 17 subjects overall, thus, I am looking for a function where I can define the data frame and the threshold values, and it will return the first OD value where it exceeds the defined thresholds (all_threshold$sup_2_minus) and (all_threshold$sup_2_plus) and its corresponding time.
I have tried subset
a advised elsewhere:
subset(lbnp_br, lbnp_br$OD < all_threshold$sup_2_minus & lbnp_br$OD > all_threshold$sup_2_plus)
However, this doesn't return what I am looking for.
and also
ifelse(lbnp_br$OD > all_threshold$sup_2_plus & lbnp_br$OD < all_threshold$sup_2_minus, lbnp_br$OD, NA)
which returns NA and doesn't specify the exact value of OD and the time.
This is not a short answer, but hopefully clear. It uses the dplyr package:
This will sort (arrange) your data based on time, subset (filter) your data for values of OD below the threshold, take the first value (slice), and return it.
A one liner:
Gives a warning and
NA
if there is no such row in the data frame, which is probably what you want.An alternative,
purrr
-based solution:which returns
NULL
if nothing is found, more correct I guess.Using the above code, I added a few extra conditions to get exactly what I was looking for and here it is for anyone who may need something similar:
which gives