How to get rows of a dataframe that contain values between two other values?

大兔子大兔子 提交于 2019-12-11 04:04:02

问题


So I want to find values in a column of a data.frame, which are in range of defined values:

  example
 [1] 6 2 4 3 5 1
 pos
 [1] 1 3 2

I now want to get the values of example for which BOTH of the following statements are TRUE, so that I got only values that lie between pos - 1 and pos +1:

if(example < pos - 1)
if(example > pos + 1)

And now the real values for my task are within a data.frame. How do I extract the complete rows, which contain these values and build a new pos data.frame.

The expected output for the example would be:

result
[1] 2 3 1

Thanks in advance!


回答1:


Set min and max thresholds and then compare each element against them

maxind <- max(pos + 1)
minind <- min(pos - 1)

Then

example[sapply(example, function(x) x > minind & x < maxind)]
## [1] 2 3 1

Or, similarly

example[example > minind & example < maxind]
## [1] 2 3 1

Or using data.table

library(data.table)
example[between(example, minind, maxind, incbounds = FALSE)]
## [1] 2 3 1



回答2:


So the solution as suggested by @David Arenburg is like this:

indx <- sapply(example[, 4], function(x) any(x < pos + 1) & any(x > pos - 1)) 

Then just do

example[indx,]

This will search a data.frame in the specified column for values that are in the defined range and will just give you the rows of your desire!



来源:https://stackoverflow.com/questions/30025358/how-to-get-rows-of-a-dataframe-that-contain-values-between-two-other-values

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!