Question

I'm trying to write a function that will add a list element to another list if that list element is less than any previous value in the list. I have a non-vectorized version that works:

myList <- c(14, 35, 12, 54, 67, 8, 32, 3, 78)

minVec <- function(x){
# Return a list of all numbers from x which are less than any previous number in the list
  outList <- list(x[1])
  for(i in 2:length(x)){
    if(x[i] < min(x[1:i - 1])){
      outList <- c(outList, x[i])}
  }
  return(unlist(outList))
}

minVec(myList)

But I need to do this many times over many lists and I want to use lapply to speed it up. The problem is that for each element n of list x I need to be able to find the min of the subset x[1:n - 1]. Can this be done in lapply (or otherwise vectorized)? How do I say "for each element of this list add the element to a new list if the element is less than any previous value in the list"?

Was it helpful?

Solution

You are looking for :

unique(cummin(myList))

EDIT some explanation:

the min of the subset x[1:n - 1] for each n of list is the cumulative minima of the list. Since cummin is vectorized , the result have the same size of the input list, so we need unique to remove deplicated.

The same solution can be generalized for :

  • cumulative maxima : cummax
  • cumulative sum : cumsum
  • cumulative product : cumprod
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top