2011-03-15 33 views
1

有什麼方法可以實現以下矢量化?向量化這個for循環:將函數應用於子索引?

# x: some vector 
# index: some vector of indeces 
n <- length(index) 
y <- rep(NA, n) 
for (i in 1:n) { 
    y[i] = myfunction(x[1:index[i]) 
} 

基本上,我想申請myfunction到矢量x的各種子集。它看起來並不像apply函數是用來處理這個問題的。

回答

2

我不知道如果我理解你正在做什麼,但如果你想從x載體,以獲得第一index -es元素的數量,多補一些樣本數據:

x <- runif(10) 
index <- c(2,5,4,8) 

並嘗試:

> lapply(index, function(index) return(x[1:index])) 
[[1]] 
[1] 0.3869757 0.4060021 

[[2]] 
[1] 0.3869757 0.4060021 0.4843015 0.2064443 0.4614179 

[[3]] 
[1] 0.3869757 0.4060021 0.4843015 0.2064443 

[[4]] 
[1] 0.3869757 0.4060021 0.4843015 0.2064443 0.4614179 0.9278044 0.7351291 
[8] 0.9792204 
+0

謝謝。這樣可行。正是我在找什麼。 – lowndrul 2011-03-16 02:59:40