Search code examples
rfunctioncurve

finding a y value whose x value is closest to zero in R vectors


I have two columns of numbers. First column is called ddd and second column post. You can easily import my data into your Rstudio this way:

id <- "0B5V8AyEFBTmXM1VIYUYxSG5tSjQ"
Points <- read.csv(paste0("https://docs.google.com/uc?id=",id,"&export=download")) 

My question is how I can find out first, what is post when ddd is 0 AND second, if there is no 0 for post when ddd is 0, find the closest to 0? (so I need R to do the both checks for me?)

I have used the following R code which doesn't work:

Points$post[Points$ddd == 0]

Solution

  • If you have a Points dataframe with two columns, post and ddd, zero or near zero could be acheived with which.min(abs(Points$ddd)) which will return the index so Points$post[which.min(abs(Points$ddd))] should get you there.

    Note, you will have issues if you have multiple zeros or minimum values.