开发者

Why doesn't this object get assigned in this `if` statement in R?

I am trying to learn R by workin开发者_Go百科g through this ProjectEuler problem using R.

If I use cat in my function I can get the list of correct values:

> n <- 1:9
> s <- 0
> ck <- function(n)
+   for(i in n) 
+     if(i/3 == round(i/3) | i/5 == round(i/5)) cat(i) 
> ck(n) 
3569> 

but if I try to assign these to an object to sum them it doesn't work:

> n <- 1:9
> s <- 0
> ck <- function(n)
+   for(i in n) 
+     if(i/3 == round(i/3) | i/5 == round(i/5)) s <- c(s, i) 
> ck(n)
> s
[1] 0
>

Why doesn't the second function work?

Thank you.


Global / local confusion. Define s inside of ck(), and return it. Something like

   ck <- function(n) {
     s <- 0
     for(i in n) {  
       if(i/3 == round(i/3) | i/5 == round(i/5)) {
         s <- c(s, i) 
       }
     }
     s
   }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜