Vectorize this for loop: applying a function to sub-indices?
Is there some way to vectorize the following?
# 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])
}
Basically, I'd like to app开发者_C百科ly myfunction
to various subsets of the vector x
. It doesn't seem like the apply
functions are built to handle this.
I am not sure if I understand what you are up to, but if you want to get from the x
vector the first index
-es number of elements, than make up some sample data:
x <- runif(10)
index <- c(2,5,4,8)
And try:
> 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
精彩评论