简体   繁体   English

在R中矢量化循环

[英]Vectorizing a loop in R

There must be a simple way to vectorize the following loop in R, but I can't see it. 必须有一种简单的方法来对R中的后续循环进行矢量化,但我看不到它。

w <- numeric(10)
z <- rnorm(20)
v <- c(sample(1:10,10),sample(1:10,10)) #Random ordering of c(1:10,1:10)
for(i in 1:10)
    w[i] <- sum(z[v==i])

另一种方法

w = rowsum(z, v)

You could use aggregate: 你可以使用聚合:
aggregate(z, by=list(v), sum) aggregate(z,by = list(v),sum)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM