2016-03-01 48 views
0

我正在寫一個置換函數如何重新安排一個函數內的變量表?

permutation<-function(seed,treatment,block_number,block_sizes,sample.size){ 
    b<-block_number 
    s<-block_sizes ## number of subjects per block 
    set.seed(seed) 
    m<-sample(s,size=b,replace = T) ## how the block is assigned 
    treats<-vector("list",b) 
    for (i in 1:b){ 
    treats[[i]]<-sample(rep(treatment,each=m[i]))## permutation within each block 
    } 
    assign<-unlist(treats)[1:sample.size] 
    table<-data.frame(cbind(as.numeric(c(1:sample.size)),assign)) 
    return(table) 
} 

permutation(seed=1,treatment=c('a',"b"),block_number=4,block_sizes=c(2,3),sample.size = 15) 

我的輸出是一個數據幀是這樣的:

V1 assign 
1 1  a 
2 2  b 
3 3  a 
4 4  b 
5 5  b 
6 6  a 
7 7  b 
8 8  a 
9 9  b 
10 10  a 
11 11  b 
12 12  b 
13 13  a 
14 14  a 
15 15  a 

我要的是黃泥重新排列輸出表,在這樣的格式(1,2,3中的圖片應該是A,b以我爲例):

enter image description here

我試着取出表,可以使用subset()和cbind()強制組合這兩列,但我不知道如何在函數內寫入它。

回答

1

我不確定在表中放置不同長度的矢量是否是一種好的做法。相反,您可以使用一個列表,每個處理都有一個元素。

但是,你可以修改你的函數來處理這兩種情況與布爾參數。我使用庫plyr來處理類似l*ply的函數,因爲我發現它們對於處理輸入和輸出類型非常有用。我用plyr::顯式調用函數。當然,您可以使用lapply並根據需要轉換爲矢量,列表或表格。然後用參數table = TRUE

permutation<-function(seed,treatment,block_number,block_sizes,sample.size, table = FALSE){ 
    b<-block_number 
    s<-block_sizes ## number of subjects per block 
    set.seed(seed) 
    m<-sample(s,size=b,replace = T) ## how the block is assigned 
    treats<-vector("list",b) 
    for (i in 1:b){ 
    treats[[i]]<-sample(rep(treatment,each=m[i]))## permutation within each block 
    } 
    assign<-unlist(treats)[1:sample.size] 

    lres <- setNames(plyr::llply(treatment, function(treat) which(assign == treat)), treatment) 

    if(table){ 
    nrow <- max(plyr::laply(lres, length)) 
    DF <- plyr::llply(lres, function(x) { 
     vec <-vector("character", nrow) 
     vec[1:length(x)] <- x 
     vec 
    }) 
    return(as.data.frame(DF)) 
    } 
    lres 
} 

你就必須要與emply細胞(""

library(plyr) 
permutation(seed=1, treatment=c('a',"b"), block_number=4, block_sizes=c(2,3), sample.size = 15, table = TRUE) 
#> a b 
#> 1 1 2 
#> 2 3 4 
#> 3 6 5 
#> 4 8 7 
#> 5 10 9 
#> 6 13 11 
#> 7 14 12 
#> 8 15 

然而,似乎好於不同長度元素的情況下使用列表中的表。 (table = FALSE

library(plyr) 
permutation(seed=1, treatment=c('a',"b"), block_number=4, block_sizes=c(2,3), sample.size = 15, table = FALSE) 
#> $a 
#> [1] 1 3 6 8 10 13 14 15 
#> 
#> $b 
#> [1] 2 4 5 7 9 11 12