我想生成 sequential citation numbers对于 R 中的数字。如果数字是连续的,则数字应以连字符分隔。否则,数字用逗号分隔。例如,数字 1、2、3、5、6、8、9、10、11 和 13
应显示为 1-3,5,6,8-11,13
。
这个问题已经previously answered for c# ,并且我已经编写了一个适用于 R 的函数,但是这个函数可以改进。我发布这个问题作为其他可能有类似需求的人的引用。如果您发现 R 的类似问题(我没有),请投票关闭,我将删除该问题。
下面的函数不是很优雅,但似乎可以完成工作。 如何让函数更短更优雅?
x <- c(1,2,3,5,6,8,9,10,11,13)
library(zoo) ## the function requires zoo::na.approx function
##' @title Generate hyphenated sequential citation from an integer vector
##' @param x integer vector giving citation or page numbers
##' @importFrom zoo na.approx
seq.citation <- function(x) {
## Result if lenght of the integer vector is 1.
if(length(x) == 1) return(x) else {
## Sort
x <- sort(x)
## Difference
df <- diff(x)
## Index to determine start and end points
ind <- c("start", rep("no", length(df)-1), "end")
ind[which(df > 1)] <- "end"
## Temporary start point vector
sts <- which(ind == "end") + 1
ind[sts[sts < length(ind)]] <- "start"
## Replace the first index element
ind[1] <- "start"
## Replace the last index element, if preceding one is "end"
if(ind[length(ind)-1] == "end") ind[length(ind)] <- "start"
## Groups for comma separation using "start" as the determining value.
grp <- rep(NA, length(x))
grp[which(ind == "start")] <- 1:length(grp[which(ind == "start")])
grp <- zoo::na.approx(grp, method = "constant", rule = 2)
## Split sequences by group
seqs <- split(x, grp)
seqs <- lapply(seqs, function(k) {
if(length(k) == 1) k else {
if(length(k) == 2) paste(k[1], k[2], sep = ",") else {
paste(k[1], k[length(k)], sep = "-")
}}
})
## Result
return(do.call("paste", c(seqs, sep = ",")))
}
}
seq.citation(x)
# [1] "1-3,5,6,8-11,13"
最佳答案
您可以使用 tapply
通过 base R 轻松完成此操作,
paste(tapply(x, cumsum(c(1, diff(x) != 1)), function(i)
ifelse(length(i) > 2, paste0(head(i, 1), '-', tail(i, 1)),
paste(i, collapse = ','))), collapse = ',')
[1] "1-3,5,6,8-11,13"
关于r - R : separate numbers by hyphen, 中的连续引用编号如果是连续的 - 如果不是则添加逗号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45589401/