2015-11-06 160 views
0

我仍然得到有R交手並相繼成立專門寫一個函數,其中如果xy是矢量任務循環&倍數:所有功能與R中

x <- c(3,7,9) 
y <- 20 

...然後的x並且其小於yx倍數需要在一個載體的形式輸出,例如:

v1 <- c(3,6,7,9,12,14,15,18) 

但隨後在函數內它需要在VEC總結所有的數字tor v1 - (3+6+...+15+18)

我已經去過了,但如果有其他的陳述,我永遠無法得到我的頭,所以任何人都可以幫我解釋,所以我知道將來的參考?

+1

下一次,當您發佈添加問題至今你已經嘗試過的東西。檢查[這個SO問題](https://stackoverflow.com/questions/8904662/simple-if-else-loop-in-r)更多關於「如果else」在R. –

回答

0

無需要循環分支。弄清楚每個x值多少次進入y,然後生成唯一的號碼清單:

x <- c(3,7,9) 
y <- 20 

possible <- y %/% x 
#[1] 6 2 2 

out <- unique(sequence(possible) * rep(x,possible)) 
# or alternatively 
# out <- unique(unlist(Map(function(a,b) sequence(a) * b, possible, x))) 
out 
#[1] 3 6 9 12 15 18 7 14 
sum(out) 
#[1] 84 
0

下面是一個使用基本循環的例子,如果在其他R.

x <- c(3,7,9) 
y1 <- 20 
v1 <- numeric() 
for(i in x){ 
    nex <- i 
    counter <- 1 
    repeat{ 
     if(!(nex %in% v1)){ 
      v1 <- c(v1, nex) 
     } 
     counter <- counter + 1 
     nex <- i*counter 
     if(nex >= y1){ 
      break 
     } 
    } 
} 
v1 <- sort(v1) 
v1.sum <- sum(v1) 

v1 
## 3 6 7 9 12 14 15 18 
v1.sum 
## 84