如何获取包含两个其他值之间的值的数据框行?
How to get rows of a dataframe that contain values between two other values?
所以我想在 data.frame 的列中查找值,这些值在定义值的范围内:
example
[1] 6 2 4 3 5 1
pos
[1] 1 3 2
我现在想获取以下两个语句都为 TRUE 的示例的值,以便我只获取介于 pos - 1
和 pos +1
之间的值:
if(example < pos - 1)
if(example > pos + 1)
现在我的任务的实际价值在 data.frame 之内。如何提取包含这些值的完整行并构建新的 pos
data.frame
.
该示例的预期输出为:
result
[1] 2 3 1
提前致谢!
所以@David Arenburg 建议的解决方案是这样的:
indx <- sapply(example[, 4], function(x) any(x < pos + 1) & any(x > pos - 1))
然后
example[indx,]
这将在指定列中搜索 data.frame 以查找定义范围内的值,并且只会为您提供所需的行!
设置最小和最大阈值,然后将每个元素与它们进行比较
maxind <- max(pos + 1)
minind <- min(pos - 1)
然后
example[sapply(example, function(x) x > minind & x < maxind)]
## [1] 2 3 1
或者,类似地
example[example > minind & example < maxind]
## [1] 2 3 1
或使用data.table
library(data.table)
example[between(example, minind, maxind, incbounds = FALSE)]
## [1] 2 3 1
所以我想在 data.frame 的列中查找值,这些值在定义值的范围内:
example
[1] 6 2 4 3 5 1
pos
[1] 1 3 2
我现在想获取以下两个语句都为 TRUE 的示例的值,以便我只获取介于 pos - 1
和 pos +1
之间的值:
if(example < pos - 1)
if(example > pos + 1)
现在我的任务的实际价值在 data.frame 之内。如何提取包含这些值的完整行并构建新的 pos
data.frame
.
该示例的预期输出为:
result
[1] 2 3 1
提前致谢!
所以@David Arenburg 建议的解决方案是这样的:
indx <- sapply(example[, 4], function(x) any(x < pos + 1) & any(x > pos - 1))
然后
example[indx,]
这将在指定列中搜索 data.frame 以查找定义范围内的值,并且只会为您提供所需的行!
设置最小和最大阈值,然后将每个元素与它们进行比较
maxind <- max(pos + 1)
minind <- min(pos - 1)
然后
example[sapply(example, function(x) x > minind & x < maxind)]
## [1] 2 3 1
或者,类似地
example[example > minind & example < maxind]
## [1] 2 3 1
或使用data.table
library(data.table)
example[between(example, minind, maxind, incbounds = FALSE)]
## [1] 2 3 1