kicpereniek
kicpereniek

Reputation: 47

R Conditional summing

I've just started my adventure with programming in R. I need to create a program summing numbers divisible by 3 and 5 in the range of 1 to 1000, using the '%%' operator. I came up with an idea to create two matrices with the numbers from 1 to 1000 in one column and their remainders in the second one. However, I don't know how to sum the proper elements (kind of "sum if" function in Excel). I attach all I've done below. Thanks in advance for your 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)

Upvotes: 0

Views: 163

Answers (2)

Sowmya S. Manian
Sowmya S. Manian

Reputation: 3833

See if this helps

x =1:1000                  ## Store no. 1 to 1000 in variable x
x                          ## print x
Div = x[x%%3==0 & x%%5==0] ## Extract Nos. divisible by 3 & 5 both b/w 1 to 1000
Div                      ## Nos. Stored in DIv which are divisible by 3 & 5 both
length(Div) 
table(x%%3==0 & x%%5==0)   ## To see how many are TRUE for given condition
sum(Div)                 ## Sums up no.s divisible by both 3 and 5 b/w 1 to 1000

Upvotes: 1

Frank
Frank

Reputation: 66819

Mathematically, the best way is probably to find the least common multiple of the two numbers and check the remainder vs that:

# borrowed from Roland Rau
# http://r.789695.n4.nabble.com/Greatest-common-divisor-of-two-numbers-td823047.html
gcd <- function(a,b) if (b==0) a else gcd(b, a %% 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 your s is every number from 1 to 1000, you could instead do

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

Just use sum on either result if that's what you want to do.

Props to @HoneyDippedBadger for figuring out what the OP was after.

Upvotes: 1

Related Questions