我在列表中有一些数据需要查找连续的整数运行(我的脑子想rle但不知道如何在这里使用它).
查看数据集并解释我所追求的内容会更容易.
这是数据视图:
$greg
[1] 7 8 9 10 11 20 21 22 23 24 30 31 32 33 49
$researcher
[1] 42 43 44 45 46 47 48
$sally
[1] 25 26 27 28 29 37 38 39 40 41
$sam
[1] 1 2 3 4 5 6 16 17 18 19 34 35 36
$teacher
[1] 12 13 14 15
Run Code Online (Sandbox Code Playgroud)
期望的输出:
$greg
[1] 7:11, 20:24, 30:33, 49
$researcher
[1] 42:48
$sally
[1] 25:29, 37:41
$sam
[1] …Run Code Online (Sandbox Code Playgroud) 我想为R中的数字生成连续引用数字.如果数字是连续的,则数字应用连字符分隔.否则数字用逗号分隔.例如,数字1, 2, 3, 5, 6, 8, 9, 10, 11 and 13应该是1-3,5,6,8-11,13.
这个问题之前已经回答过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 <- …Run Code Online (Sandbox Code Playgroud)