如何在 R 中按国会图书馆分类 (LCC) 编号排序



美国国会图书馆 分类号在图书馆中用于为事物提供呼叫号码,以便将它们订购在书架上。它们可以很简单,也可以相当复杂,有一些强制性部分,但许多是可选的。(请参阅050国会图书馆呼叫号码上的"在050中输入呼叫号码"以了解它们如何分解,或lc_callnumber有关对它们进行排序的Ruby工具。

我想在 R 中按 LCC 编号排序。我已经查看了对 R 中的非平凡元素列表进行排序和对 R 中自定义类的元素列表列表进行排序?但还没有弄清楚。

以下是按排序顺序输入的四个呼叫号码:

call_numbers <- c("QA 7 H3 1992", "QA 76.73 R3 W53 2015", "QA 90 H33 2016", "QA 276.45 R3 A35 2010")

sort按字符对它们进行排序,因此 276 <7 <76.73 <90。

> sort(call_numbers)
[1] "QA 276.45 R3 A35 2010" "QA 7 H3 1992"          "QA 76.73 R3 W53 2015"  "QA 90 H33 2016"       

为了正确排序它们,我想我必须定义一个类,然后定义一些方法,如下所示:

library(stringr)
class(call_numbers) <- "LCC"
## Just pick out the letters and digits for now, leave the rest
## until sorting works, then work down more levels.
lcc_regex <- '([[:alpha:]]+?) ([[:digit:]\.]+?) (.*)'
"<.LCC" <- function(x, y) {
x_lcc <- str_match(x, lcc_regex)
y_lcc <- str_match(y, lcc_regex)
if(x_lcc[2] < y_lcc[2]) return(x)
if(as.integer(x_lcc[3]) < as.integer(y_lcc[3])) return(x)
}
"==.LCC" <- function(x, y) {
x_lcc <- str_match(x, lcc_regex)
y_lcc <- str_match(y, lcc_regex)
x_lcc[2] == y_lcc[2] && x_lcc[3] == y_lcc[3]
}
">.LCC" <- function(x, y) {
x_lcc <- str_match(x, lcc_regex)
y_lcc <- str_match(y, lcc_regex)
if(x_lcc[2] > y_lcc[2]) return(x)
if(as.integer(x_lcc[3]) > as.integer(y_lcc[3])) return(x)
}

这不会更改排序顺序。我还没有定义一个子集方法("[.myclass"(,因为我不知道它应该是什么。

这可能是一种更简单的方法。 这假设每个数字都有以下格式:2 个字母的代码、空格、数字、空格、字母数字、空格...年。

该策略是将LOC编号按空格分割,然后获得前3个字段的3列数据,然后可以使用order函数按顺序对每列进行排序。

call_numbers <- c("QA 7 H3 1992", "QA 76.73 R3 W53 2015", "QA 90 H33 2016", "QA 276.45 R3 A35 2010")
#split on the spaces
split<-strsplit(call_numbers, " " )
#Retrieve the 2 letter code
letters<-sapply(split, function(x){x[1]})
#retrieve the 2nd number group and convert to numeric values for sorting
second<-sapply(split, function(x){as.numeric(x[2])})
#obtain the 3rd grouping
third<-sapply(split, function(x){x[3]})
#find the year
year<-sapply(split, function(x){x[length(x)]})
df<-data.frame(call_numbers)
#sort data based on the first and 2nd column
call_numbers[order(letters, second, third)]

对于这个有限的数据集,该技术有效。

我觉得我花了太多时间来找出你想要做的事情的解决方案——只有我的是针对 JavaScript 的。但它基本上归结为这些数字的"规范化"概念,以便它们可以按字母顺序排序。

也许可以使用此解决方案并将其移植到 R。至少,希望这能让你开始。它涉及一些正则表达式和一些额外的脚本,以使呼叫号码进入可以排序的状态。

https://github.com/rayvoelker/js-loc-callnumbers/blob/master/locCallClass.js

祝你好运!

最简单(和优雅(的方式:使用 packgstringr中的str_sort

# install.packages("stringr") ## Uncomment if not already installed
library(stringr)
str_sort(call_numbers, numeric = TRUE)
[1] "QA 7 H3 1992"          "QA 76.73 R3 W53 2015"  "QA 90 H33 2016"       
[4] "QA 276.45 R3 A35 2010"

gtools包中的mixedsort原来可以做到这一点:

library(gtools)
call_numbers <- c("QA 7 H3 1992", "QA 76.73 R3 W53 2015", "QA 90 H33 2016", "QA 276.45 R3 A35 2010")
mixedsort(call_numbers)
## [1] "QA 7 H3 1992"          "QA 76.73 R3 W53 2015"  "QA 90 H33 2016"        "QA 276.45 R3 A35 2010"

此外,mixedorder可用于按一列对数据框进行排序。

这是前面在如何对元素在 R 中包含字母和数字的字符向量进行排序中回答的特例?

最新更新