[R] avoid a loop

Gabor Grothendieck ggrothendieck at gmail.com
Fri May 29 01:07:14 CEST 2009


Try this:

> sapply(1:n, function(i) sum(abs(outer(a, b, "-")-i)==0))
[1] 10 10 10 10  9


On Thu, May 28, 2009 at 5:45 PM, KARAVASILIS GEORGE <gkaravas at ee.duth.gr> wrote:
> Hello, R users.
> I have the following code:
>
> a=1:10
> b=-3:15
> n=5
> x <- rep(0,n)
> for (i in 1:n) x[i] <- sum( outer(a,b, function(s,t)  abs(a-b-i)==0) )
>
> Can someone tell me if I could avoid the for command?
>
> Thank you in advance.
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>




More information about the R-help mailing list