向量索引函数R.

时间:2014-06-19 16:46:21

标签: r

我正在尝试在R中编写一个函数来查看列表的元素,并确定该值是否已从其先前的状态更改。所以列表

2 2 3 2 5

该函数将返回一个p-1布尔向量

TRUE FALSE FALSE FALSE
到目前为止,myy code / pseudo code是这样的:

did.change<-function(lst){
  final.vect=vector()
  compare=lst
  for (item in lst){
    if (we are on the first item){
      next
    }
    else if (i==previous i){
      final.vect=c(final.vect, FALSE)
    }
    else{
      final.vect=c(final.vect, TRUE)
    }
  }
  return(final.vect)
}

是否有跟踪列表索引的功能?这样我可以为我的第一个语句

if(index(lst)==1)之类的事情

2 个答案:

答案 0 :(得分:4)

如我的评论中所述,

head(x,-1) == tail(x,-1)

可能就是你所需要的。一个更详细的版本是:

x[1:(length(x)-1)] == x[2:length(x]

答案 1 :(得分:1)

你可以使用diff(x) == 0,虽然@joran的解决方案更快:

set.seed(42)
x <- sample(1:5, 1e4, TRUE)

library(microbenchmark)
microbenchmark(diff(x) == 0,
               head(x,-1) == tail(x,-1))

#Unit: microseconds
#                       expr     min      lq   median       uq      max neval
#               diff(x) == 0 532.094 534.726 535.6365 590.5695 2063.874   100
# head(x, -1) == tail(x, -1) 284.914 286.392 287.8685 386.3660 1081.672   100