r - 如何从值的范围中找到给定的值?
问题描述
I have have the below data :
Y z
100-800 a
150-600 b
200-300 c
400-600 d
4000-12000 e
任何帮助将非常感激。
基于x的给定值(即x = 100),它应该找到Y的给定范围内的值,并给出Y和z的对应值。如果给定的x不在Y的给定范围内,那么它应该找到较近的范围并给出相应的 Y 和 Z 值。
DT[, list(OK = 1 %in% seq(Y, Y)), by = Z]
对于 X=110 的给定值
输出应该是
Y Z
100-800 a
For x=200
Y z
100-800 a
150-600 b
200-300 c
For x=12500
Y z
4000-12000 e
解决方案
We can write a helper function using tidyr::separate
to separate columns. In case if there are no indices which fall within the range we compare the value
with lowest value and highest value in the dataframe and return the row accordingly.
subset_fun <- function(df, val) {
df1 <- tidyr::separate(df, Y, c("low", "high"), sep = "-",convert = TRUE)
inds <- with(df1, val >= low & val <= high)
if (any(inds))
df[inds, ]
else if (min(df1$low) > val) df[which.min(df1$low), ]
else df[which.max(df1$high), ]
}
subset_fun(df, 100)
# Y z
#1 100-800 a
subset_fun(df, 200)
# Y z
#1 100-800 a
#2 150-600 b
#3 200-300 c
subset_fun(df, 12500)
# Y z
#5 4000-12000 e
subset_fun(df, 0)
# Y z
#1 100-800 a
data
df <- structure(list(Y = structure(1:5, .Label = c("100-800", "150-600",
"200-300", "400-600", "4000-12000"), class = "factor"),
z = structure(1:5, .Label = c("a", "b", "c", "d", "e"), class = "factor")),
class = "data.frame", row.names = c(NA, -5L))
推荐阅读
- c# - XpsDocumentWriter 正在打开一个**源**文件
- javascript - addEventListener 与 currentTarget 之间的区别
- c++ - 类和 OOP 帮助 C++
- wpf - AssemblyLoadContext.Unload 不卸载 Wpf 库
- android - 在windows 10上运行docker容器(使用VcXsrv for GUI),但是当我使用adb连接android手机时,Action交互非常非常慢
- java - 如何在公共目录中保存使用 Android 10 中 Android 默认下载管理器下载的视频?
- azure - Azure DevOps 任务如何使用上一个 Azure DevOps 任务的输出
- java - 使用 setText 将文本更改为变量标题
- node.js - 如何在 MongoDB 中使用 facet 计算百分比?
- neo4j - 如何使用 neo4j-driver 函数获得与 py2neo 中 evaluate() 函数的结果相同的结果?