R Conditional summing -


i've started adventure programming in r. need create program summing numbers divisible 3 , 5 in range of 1 1000, using '%%' operator. came idea create 2 matrices numbers 1 1000 in 1 column , remainders in second one. however, don't know how sum proper elements (kind of "sum if" function in excel). attach i've done below. in advance help!

s1<-1:1000 in<-s1%%3 m1<-matrix(c(s1,in), 1000, 2, byrow=false)  s2<-1:1000 in2<-s2%%5 m2<-matrix(c(s2,in2),1000,2,byrow=false) 

mathematically, best way find least common multiple of 2 numbers , check remainder vs that:

# borrowed roland rau # http://r.789695.n4.nabble.com/greatest-common-divisor-of-two-numbers-td823047.html gcd <- function(a,b) if (b==0) else gcd(b, %% b) lcm <- function(a,b) abs(a*b)/gcd(a,b)  s <- seq(1000) s[ (s %% lcm(3,5)) == 0 ] #  [1]  15  30  45  60  75  90 105 120 135 150 165 180 195 210 # [15] 225 240 255 270 285 300 315 330 345 360 375 390 405 420 # [29] 435 450 465 480 495 510 525 540 555 570 585 600 615 630 # [43] 645 660 675 690 705 720 735 750 765 780 795 810 825 840 # [57] 855 870 885 900 915 930 945 960 975 990 

since s every number 1 1000, instead do

seq(lcm(3,5), 1000, by=lcm(3,5)) 

just use sum on either result if that's want do.

props @honeydippedbadger figuring out op after.


Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -