R 在向量的多个子集上使用应用函数

R 在向量的多个子集上使用应用函数,r,apply,lapply,mapply,R,Apply,Lapply,Mapply,我已经为这个问题寻找了一段时间的解决方案,但似乎没有任何东西可以解决我面临的这个看似简单的问题 长话短说,我希望在向量的多个子集上运行函数,但我试图避免for循环 举个简单的例子 x <- runif(20) index <- round(runif(10,1,10)) [1] 7 8 4 6 9 3 1 2 8 7 x您仍然可以使用xapply函数。您可以尝试以下方法: set.seed(1) x <- runif(20) index <- round(runif(

我已经为这个问题寻找了一段时间的解决方案,但似乎没有任何东西可以解决我面临的这个看似简单的问题

长话短说,我希望在向量的多个子集上运行函数,但我试图避免for循环

举个简单的例子

x <- runif(20)

index <- round(runif(10,1,10))
[1] 7 8 4 6 9 3 1 2 8 7

x您仍然可以使用
xapply
函数。您可以尝试以下方法:

set.seed(1)
x <- runif(20)
index <- round(runif(10,1,10))
## [1] 5 5 9 8 4 1 4 6 3 9
sapply(index, function(n) mean(tail(x, n)))
## [1] 0.4622008 0.4622008 0.5185548 0.5222463 0.4519646 0.2787476 0.4519646
## [8] 0.4939800 0.2748015 0.5185548
希望有帮助

亚历克斯

mean(tail(x, 5))
## [1] 0.4622008
mean(tail(x, 9))
## [1] 0.5185548