[英]R sequence format from raw sequence to shortened code
In R i can write a sequence of 1 - 9 like 1:9
and it will output c(1,2,3,4,5,6,7,8,9)
.在 R 中,我可以像
1:9
一样编写 1 - 9 的序列,它将输出c(1,2,3,4,5,6,7,8,9)
。
I want to do the reverse.我想做相反的事情。 If i have a sequence of
c(1,2,3,4,5,6,7,8,9)
is there any way to get 1:9
as an output?如果我有一个
c(1,2,3,4,5,6,7,8,9)
序列,有没有办法得到1:9
作为输出? Preferably in a dynamic way, so that for example c(1,2,3,4,6,7,8,9)
becomes c(1:4, 6:9)
?最好以动态方式,例如
c(1,2,3,4,6,7,8,9)
变成c(1:4, 6:9)
?
One option could be:一种选择可能是:
sapply(split(x, cumsum(c(1, diff(x)) > 1)), function(x) paste(range(x), collapse = ":"))
0 1
"1:4" "6:9"
We can use tapply
我们可以使用
tapply
tapply(x, cumsum(c(TRUE, diff(x) > 1)), FUN =
function(x) paste(min(x), max(x), sep=":"))
# 1 2
#"1:4" "6:9"
x <- c(1,2,3,4,6,7,8,9)
Perhaps a roundabout way, but you can use the head
and tail
functions to get the first and last item of the vector.也许是一种迂回的方式,但您可以使用
head
和tail
函数来获取向量的第一项和最后一项。
> x <- c(1, 2, 3, 4, 5, 6, 7, 8, 9)
> tail(x, n=1)
[1] 9
> head(x, n=1)
[1] 1
> head(x, n=1):tail(x, n=1)
[1] 1 2 3 4 5 6 7 8 9
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.