Search code examples
rdataframeposition

finding a certain value in a data frame


I want to check the relation between two columns in my data frame and extract the last element that satisfy a certain relation.

t    x   y 
1.5 875 450
1.3 460 232
1.1 225 125
1.7 1725 900
1.6 720 460
2.0 22  14
1.7 775 450
1.5 880 450
2.4 870 455
1.1 425 220
1.8 1750 910
1.3 560 320
1.3 430 232
2.1 3090 1840
2.0 1750 7950
1.7 170 895
1.1 350 220
1.2 80 45
1.8 169 880
1.7 1700 900
1.9 230 130
2.1 540 237
0.8 50 28

so i am looking to extract the last y point that satisfy: y >= 0.45 x . The problem is that ywill keep taking different values and i want to extract only the last y value higher or equal to 0.45 x.

Thank you for your help


Solution

  • We may create the condition, extract the index with which , return the max index and use that to extract the value of 'y'

    with(df, y[max(which(y >= 0.45 *x))])
    [1] 28
    

    data

    df <- structure(list(t = c(1.5, 1.3, 1.1, 1.7, 1.6, 2, 1.7, 1.5, 2.4, 
    1.1, 1.8, 1.3, 1.3, 2.1, 2, 1.7, 1.1, 1.2, 1.8, 1.7, 1.9, 2.1, 
    0.8), x = c(875L, 460L, 225L, 1725L, 720L, 22L, 775L, 880L, 870L, 
    425L, 1750L, 560L, 430L, 3090L, 17500L, 1700L, 350L, 105L, 1690L, 
    1700L, 230L, 540L, 50L), y = c(450L, 232L, 125L, 900L, 460L, 
    14L, 450L, 450L, 455L, 220L, 910L, 320L, 232L, 1840L, 7950L, 
    895L, 220L, 45L, 880L, 900L, 130L, 237L, 28L)), 
    class = "data.frame", row.names = c(NA, 
    -23L))