首页 > 解决方案 > 在 R 中使用查找表匹配区间

问题描述

我正在寻找使用具有与标准对齐的开始和结束间隔的查找参考表(即“差”、“平均”等)

我有一个数据表,我想在其中创建一个新的标准列,根据它在查找表上的间隔标记数据值。下面是一个简化的例子。我的实际数据集要大得多并且需要是动态的,因此我不必在脚本中硬编码或创建许多单独的对象。

lookup_df = data.frame("Standard" = c("Poor", "Below_Average", "Average", "Above_Average", "Good"),
                  "Start" = c(2,3,4,5,6), "End" = c(3,4,5,6,7))

col = c(1.5, 5.2, 4.1, 3.3, 9.6, 2.4)

我正在尝试使用 ifelse() 和 findInterval() 从查找标准列返回索引。我知道问题是索引部分,因为 findInterval 返回无法索引的 0。我试图通过向 findInterval 添加 +1 来解决这个问题,但这也没有用。这是我一直在尝试的:

ifelse(findInterval(col, lookup_df$End)+1 > 1, lookup_df$Standard[findInterval(col, lookup_df$End)+1], "Poor")

# [1] "Poor"          "Above_Average" "Average"       "Below_Average"
# [5] NA              "Poor"   

我想要的结果是:

# [1] "Poor"          "Above_Average" "Average" "Below_Average"      
# [5] "Good"             "Poor"

我已尝试使用此示例中的 transform() 将间隔与 R 中另一个表中的值匹配,但也无法使其正常运行。

ifelse() 索引问题似乎与通过索引从另一个向量返回的 ifelse 返回值一致

我猜这里有一个我缺少的简单解决方案!任何帮助表示赞赏。

编辑以包括最终答案

这是我基于 R. Lima 的解决方案使用的最终解决方案,用于合并到 dplyr 中:

lookup_vec = as.character(lookup_df$Standard)
names(lookup_vec) <- c("0", "1", "2", "3","4")

df = data.frame(col = c(1.5, 5.2, 4.1, 3.3, 9.6, 2.4))

df = df %>%
  mutate(Standard = stringr::str_replace_all(
    findInterval(col, lookup_df$Start[-1]), lookup_vec))

标签: rif-statementindexinglookupintervals

解决方案


This should do it, although I have used str_replace_all() from package stringr instead of ifelse(). This functions handles the zero problem you mentioned.

There is probably a more elegant and faster way to do it, but this one does the trick.

# Defining the lookup reference object
lookup <- c("Poor", "Below_Average", "Average", "Above_Average", "Good")
names(lookup) <- c("0", "1", "2", "3","4")

# Defining your data frame
df <- data.frame(col = c(1.5, 5.2, 4.1, 3.3, 9.6, 2.4))

# Classifying the data and inserting into your data frame
df$classes <- stringr::str_replace_all(
  findInterval(df$col, c(3,4,5,6)), lookup)
df$classes

[1] "Poor"          "Above_Average" "Average"       "Below_Average" "Good"         
[6] "Poor"


推荐阅读