Home > Mobile >  How to extract a row by an approximate value in a column?
How to extract a row by an approximate value in a column?

Time:11-06

How can you extract a row using an approximate value in a column, such as 5? I want to extract the row with the data value closest to 5 in a certain column. enter image description here

For example, I want to extract the row with the data value closest to 5 in pro.f column.

CodePudding user response:

You can find the position of the number closest to 5 in the pro.f column using abs() along with which.min(). Then, use that as an index to extract that particular row.

df[which.min(abs(df$pro.f - 5)),]

Output

  var freq pro.f
3 328   12  5.09

Data

structure(list(
  var = c(326, 327, 328),
  freq = c(10, 11, 12),
  pro.f = c(4.24, 4.65, 5.09)
),
class = "data.frame",
row.names = c(NA,-3L))

CodePudding user response:

In dplyryou can use slice_min:

df %>%
  slice_min(abs(pro.f - 5))
  var freq pro.f pro.f_temp
1 328   12  5.09       0.09

Data:

df <- data.frame(
  var = c(326, 327, 328, 322, 321),
  freq = c(10, 11, 12, 10, 11),
  pro.f = c(4.24, 4.65, 5.09, 5.10, 5.11)
)
  •  Tags:  
  • r
  • Related