确定R中是否所有值都是相邻的整数

时间:2012-03-16 15:46:21

标签: r integer

我正在尝试测试对象中的所有值(如果已排序)是否是相邻的整数值。例如:

x <- c(1,2,3)
is.adjacent(x)
TRUE

y <- c(1,2,4)
is.adjacent(y)
FALSE

z <- c(4,2,1,3)
is.adjacent(z)
TRUE

关于好方法的任何想法?

1 个答案:

答案 0 :(得分:7)

这是一个解决方案。我已经构造了它,它将为包含一组连续整数的向量返回TRUE,即使它们中的一些被重复(例如c(1,3,2,1,1,1))。如果您希望在这种情况下返回FALSE,只需删除调用unique()的部分。

is.adjacent <- function(X) {
    all(diff(sort(unique(X))) == 1)
}

# Try it out
x <- c(1,2,3)
y <- c(1,2,4)
z <- c(4,2,1,3)

is.adjacent(x)
is.adjacent(y)
is.adjacent(z)