2015-09-20 27 views
0

我想創建一個函數,該函數可以查找連續增加k倍的向量的分量。查找連續增加k倍的向量的分量

也就是說,如果做作功能是f(x,k)x=c(2,3,4,3,5,6,5,7),然後 的f(x,1)值是因爲只有這些的x增加1個時間分量2,3,3,5,5

此外,如果k=2,則f(x,2)值爲2,3因爲只有這些組件通過2次持續增加。(2→3→4和3'→5→6)

我想我應該爲此使用重複的語法,如for

回答

2

1)使用rollapply動物園包:

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

現在測試出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)這種變化是略短,也可以工作:

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

2)這裏是一個版本1A的使用沒有軟件包:

f3 <- function(x, k) head(x, -k)[ apply(embed(diff(x) > 0, k), 1, all) ] 
0

我不太明白你的問題的第二部分(即具有k = 2),但第一部分,你可以使用這樣的:從

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 
+0

謝謝你的回答。我的意思是函數f(x,k)發現向量x的分量單調增加而不停止k次。因此,在上述情況下,f(x,3)爲NULL,因爲沒有x的分量增加而沒有停止三次。在k> = 4中,情況相同,即NULL。謝謝。 – kmee

1

一個完全量化的解決方案:

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)