在R中搜索某个数字向量

时间:2014-12-31 03:19:25

标签: r search numbers

我有一个数字向量列表,如下所示:

[[1]]
[1] 0 1

[[2]]
[1] 0 1

[[3]]
[1] 1 0

[[4]]
[1] 1 0

我是R的新手,谁能告诉我我可以用什么函数来计算最后一次出现的块号

number of the last occurrence  "[0,0]"=0
number of the last occurrence  "[0,1]"=2
number of the last occurrence  "[1,0]"=4
number of the last occurrence  "[1,1]"=0

提前致谢!

3 个答案:

答案 0 :(得分:3)

没有内置任何东西(AFAIK),但它是一个非常简单的构建功能:

dat <- list(c(0,1), c(0,1), c(1,0), c(1,0))

lastBlock <- function(val) {
  val <- tail(which(sapply(dat, function(x) all(x==val))), 1)
  ifelse(length(val)==0, 0, val)
}

lastBlock(c(0,0))
## [1] 0

lastBlock(c(0,1))
## [1] 2

lastBlock(c(1,0))
## [1] 4

lastBlock(c(1,1))
## [1] 0

答案 1 :(得分:2)

@ hrbrmstr的lastBlock的另一个变体是:

 lastBlock <- function(lst, val){
   do.call(pmax, as.list(c(0, which(vapply(lst,
                       function(x) all(x==val), logical(1L))))))
    }
lastBlock(dat, c(1,0))
#[1] 4
lastBlock(dat, c(0,0))
#[1] 0
lastBlock(dat, c(0,1))
#[1] 2

更新

如果您希望search有多套val

 lastBlock1 <- function(lst, searchDat){
    s1 <- sapply(lst, paste, collapse=",")
    s2 <- do.call(paste, c(searchDat, list(sep=',')))
    indx <- outer(s2, s1, `==`)
    res <- do.call(`pmax`, as.data.frame(col(indx)*indx))
    cat(paste0('number of the last occurence ', "'[", s2, "]' = ",
                   res, collapse="\n"),'\n')
  }     

   lastBlock1(dat,dat2)
   #number of the last occurence '[0,0]' = 0
   #number of the last occurence '[1,0]' = 4
   #number of the last occurence '[0,1]' = 2
   #number of the last occurence '[1,1]' = 0 

或使用match的上述方法的变体(会更快)。归功于@alexis_laz

  lastBlock2 <- function(lst, searchDat){
    s1 <- sapply(lst, paste, collapse=",")
    s2 <- do.call(paste, c(searchDat, list(sep=',')))
    res <- (length(s1)+1) - match(s2, rev(s1), nomatch=length(s1)+1)
    cat(paste0('number of the last occurence ', "'[", s2, "]' = ",
                   res, collapse="\n"),'\n')
  }     

 lastBlock2(dat,dat2)
 #number of the last occurence '[0,0]' = 0
 #number of the last occurence '[1,0]' = 4
 #number of the last occurence '[0,1]' = 2
 #number of the last occurence '[1,1]' = 0 

数据

dat <- list(c(0,1), c(0,1), c(1,0), c(1,0)) 
dat2 <- expand.grid(rep(list(0:1),2))

答案 2 :(得分:1)

这是另一种可能性

## your list
x <- list(c(0,1), c(0,1), c(1,0), c(1,0))
## list of vectors for comparison
comp <- list(c(0,0), c(0,1), c(1,0), c(1,1))

duplicatedidentical会有所帮助。首先我们确定相同的元素,然后我们找到它们的重复项,并用重复的索引替换索引值。

m <- mapply(identical, x, comp)
replace(as.numeric(m), m, which(duplicated(x)))
#[1] 0 2 4 0