0

I want to create a function which finds components of a vector which increase continually by k-times.

That is, if the contrived function is f(x,k) and x=c(2,3,4,3,5,6,5,7), then the value of f(x,1) is 2,3,3,5,5 since only these components of x increase by 1 time.

In addition, if k=2, then the value of f(x,2) is 2,3 since only these components increase continually by 2 times.(2→3→4 and 3→5→6)

I guess that I ought to use repetitive syntax like for for this purpose.

David Arenburg
  • 91,361
  • 17
  • 137
  • 196
kmee
  • 151
  • 7

3 Answers3

2

1) Use rollapply from the zoo package:

library(zoo)
f <- function(x, k)
       x[rollapply(x, k+1, function(x) all(diff(x) > 0), align = "left", fill = FALSE)]

Now test out f:

x <- c(2,3,4,3,5,6,5,7)

f(x, 1)
## [1] 2 3 3 5 5

f(x, 2)
## [1] 2 3

f(x, 3)
## numeric(0)

1a) This variation is slightly shorter and also works:

f2 <- function(x, k) head(x, -k)[ rollapply(diff(x) > 0, k, all) ]

2) Here is a version of 1a that uses no packages:

f3 <- function(x, k) head(x, -k)[ apply(embed(diff(x) > 0, k), 1, all) ]
G. Grothendieck
  • 254,981
  • 17
  • 203
  • 341
1

A fully vectorized solution:

f <- function(x, k = 1) {

  rlecumsum = function(x)
  { #cumsum with resetting
    #http://stackoverflow.com/a/32524260/1412059
    cs = cumsum(x)
    cs - cummax((x == 0) * cs)
  }

  x[rev(rlecumsum(rev(c(diff(x) > 0, FALSE) ))) >= k]
}

f(x, 1)
#[1] 2 3 3 5 5
f(x, 2)
#[1] 2 3
f(x, 3)
#numeric(0)
Roland
  • 127,288
  • 10
  • 191
  • 288
0

I don't quite understand the second part of your question (that with k=2) but for the first part you can use something like this:

test<-c(2,3,4,3,5,6,5,7) #Your vector

diff(test) #Differentiates the vector
diff(test)>0 #Turns the vector in a logical vector with criterion >0

test[diff(test)>0] #Returns only the elements of test that correspond to a TRUE value in the previous line
ECII
  • 10,297
  • 18
  • 80
  • 121
  • I thank you for your kind answer. I meant that the function f(x,k) finds the components of the vector x which increase monotonically without ceasing by k times. Hence, in the situation described above, f(x,3) is NULL since there are no components of x increasing without ceasing by three times. In k>=4, situations are the same, that is, NULL. thank you. – kmee Sep 20 '15 at 14:10