R条件求和

时间:2015-10-02 21:26:32

标签: r

我刚开始使用R编程进行冒险。我需要使用'%%'运算符创建一个程序,将可以被1和5整除的数字加在1到1000的范围内。我想出了一个想法,创建两个矩阵,一列中的数字从1到1000,第二列中的余数。但是,我不知道如何总结正确的元素(Excel中的“sum if”函数的种类)。我附上我在下面所做的一切。在此先感谢您的帮助!

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)

2 个答案:

答案 0 :(得分:1)

在数学上,最好的方法可能是找到两个数字中最不常见的倍数,并检查余数与:

color(interpret_color(sky_color))

由于您的# 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 是从1到1000的每个数字,您可以改为

s

如果您想要这样做,只需对任一结果使用seq(lcm(3,5), 1000, by=lcm(3,5))

向@HoneyDippedBadger道具,找出OP之后的内容。

答案 1 :(得分:1)

看看这是否有帮助

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
相关问题