2012-11-11 199 views
1

我有這樣一個data.frame df使用:while循環結構與`apply`

df <- data.frame (x=1:5,y=1:5) 

我想用一個apply功能逐行這個數據幀,在這裏我檢查條件取決於xy,然後更改xy元素,直到它們符合我的條件。在這個例子中,如果xy不加起來爲8,我不斷爲他們選擇新的隨機數字,然後重試。

我想函數使用while循環將是最好的。所以,我試過如下:

checkchange <- function(x) while(x[1] + x[2] < 8) 
       { 
       x[1] <- sample(5,1) 
       x[2] <- sample(5,1) 
       return(cbind(x[1],x[2])) 
     } 

然後,我會做這個計劃:

newdf <- apply(df,1,checkchange) 

這是行不通的。我應該使用repeatbreak還是需要更清楚地指定return值。我們非常感謝while循環語法。

回答

3

你缺少你的匿名函數

大括號這個工作對我來說:

checkchange <- function(x) 
       { 
       while((x[1] + x[2]) < 8) 
       { 
       x[1] <- sample(5,1) 
       x[2] <- sample(5,1) 
       } 
       return(cbind(x[1],x[2])) 
       } 
1

由於@Nico指出,該功能將與附加括號工作。

checkchange <- function(x) {  
    while (sum(x) < 8) { 
    # no need to sample from 1:5 if the sum has to be at least 8 
    x <- sample(3:5, 2, TRUE)   
    } 
    return(x) 
} 

apply的輸出需要轉置以匹配數據的原始排列。

t(apply(df, 1, checkchange)) 

順便說一句,你不需要一個循環的功能:

checkchange <- function(x) { 
if (sum(x) < 8) { 
    x[1] <- sample(3:5, 1) 
    x[2] <- ifelse(x[1] == 3, 5, sample(seq(8 - x[1], 5), 1)) 
    } 
    return(x) 
} 
+0

+1感謝斯文很大的幫助,並搶佔了我的't'。用'ifelse'也可以想到快捷鍵! – user1320502