简体   繁体   English

如何获取包含两个其他值之间的值的数据帧的行?

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

So I want to find values in a column of a data.frame, which are in range of defined values: 所以我想在data.frame的列中找到值,这些值在定义的值范围内:

  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 : 我现在想得到以下语句的BOTH为TRUE的示例值,这样我只得到位于pos - 1pos +1 pos - 1之间的值:

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

And now the real values for my task are within a data.frame. 现在我的任务的真正价值在data.frame中。 How do I extract the complete rows, which contain these values and build a new pos data.frame . 如何提取包含这些值的完整行并构建新的pos data.frame

The expected output for the example would be: 该示例的预期输出将是:

result
[1] 2 3 1

Thanks in advance! 提前致谢!

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 或者使用data.table

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

So the solution as suggested by @David Arenburg is like this: 所以@David Arenburg建议的解决方案是这样的:

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! 这将搜索指定列中的data.frame,以查找定义范围内的值,并为您提供所需的行!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM