不使用data.frame的数值的透明查找表?

rob*_*ust 6 r

Advanced R讨论了将字符子集用于查找表的想法。

x <- c("m", "f", "u", "f", "f", "m", "m")
lookup <- c(m = "Male", f = "Female", u = NA)
lookup[x]
#>        m        f        u        f        f        m        m 
#>   "Male" "Female"       NA "Female" "Female"   "Male"   "Male"
Run Code Online (Sandbox Code Playgroud)

reprex软件包(v0.2.1)创建于2019-03-04

但是,这种想法不适用于数字查找,因为names它是字符向量所必需的特殊属性。

不要求使用数字查找的简单等效解决方案是data.frame什么?

我想避免一种data.frame解决方案,因为键和值之间的映射仅基于顺序,而不是更加透明的3 = 'Excellent', 2 = 'Good', 1 = 'Poor'


data.frame字符查找表后面的段落建议使用解决方案。

grades <- c(1, 2, 2, 3, 1)

info <- data.frame(
  grade = 3:1,
  desc = c("Excellent", "Good", "Poor"),
  fail = c(F, F, T)
)

info[grades, 'desc']
#> [1] Excellent Good      Good      Poor      Excellent
#> Levels: Excellent Good Poor
Run Code Online (Sandbox Code Playgroud)

reprex软件包(v0.2.1)创建于2019-03-04

Sor*_*ren 0

您可以将数值分配给列表中的索引,并为列表索引位置分配一个值。使用您的数字索引(等级),您可以按如下方式查找值:

lookups <- list()
lookups[[1]] <- "Excellent"
lookups[[2]] <- "Good"
lookups[[3]] <- "Fair"
lookups[[4]] <- "Poor"
lookups[[5]] <- "Fail"

grades <- c(1, 2, 2, 3, 1)
lookups[grades]
Run Code Online (Sandbox Code Playgroud)

这产生了等级类别:

> lookups[grades]
[[1]]
[1] "Excellent"

[[2]]
[1] "Good"

[[3]]
[1] "Good"

[[4]]
[1] "Fair"

[[5]]
[1] "Excellent"
Run Code Online (Sandbox Code Playgroud)

或者进一步简化为命名向量:

grades <- c(1, 2, 2, 3, 1)
lookups[grades]

setNames(grades,unlist(lookups[grades]))
Run Code Online (Sandbox Code Playgroud)

产量:

> setNames(grades,unlist(lookups[grades]))
Excellent      Good      Good      Fair Excellent 
        1         2         2         3         1 
Run Code Online (Sandbox Code Playgroud)