2013-02-15 78 views
0

我有data.frame,看起來像這樣:在新數據中轉換拆分的數據幀。框架

Element1  Element2  Value   Index 
     a   cf   0.14    1   
     a   ng   0.25    1   
     a   ck   0.12    1   
     a   rt   0.59    1  
     a   pl   0.05    1   
     b   gh   0.02    2   
     b   er   0.91    2 
     b   jk   0.87    2 
     c   qw   0.23    3 
     c   po   0.15    3 

我想下面的輸出:

Element_a1  Element_a2 Value_a  Element_b1 Element_b2 Value_b 
     a   cf   0.14    b   gh  0.02  
     a   ng   0.25    b   er  0.91 
     a   ck   0.12    b   jk  0.87 
     a   rt   0.59    NA   NA  NA 
     a   pl   0.05    NA   NA  NA 

等等...

我應用「拆分」功能來分割初始數據。根據「索引」列 ,但我不能根據需要轉換拆分的data.frame(即data.frames的列表) ,因爲單個data.frames的長度不等於 。我嘗試應用(從簾布層封裝)

X = do.call(rbind.fill,SPL)

從另一文章,但返回像初始一個data.frame。

任何人都可以幫助我嗎?

最佳

F.

回答

2

這裏有一個辦法做到這一點:

nRow <- max(table(dat$Element1))   # maximum number of rows in a group 
spl2 <- by(dat, dat$Element1, FUN = function(x) {   
    if (nRow > nrow(x)) {     # insufficient number of rows? 
    subdat <- dat[seq_len(nRow - nrow(x)), ] # create a data frame 
    subdat[ , ] <- NA      # fill it with NAs 
    return(rbind(x, subdat))}  # bind it to the subset and return the result 
    return(x)        # return the subset as it is 
}) 
result <- do.call(cbind, spl2)    # bind all subsets together 
+1

+1!我會這樣做。也許你可以用''by''來替換你的分裂 - lapply,就像..'''(dat,dat $ Element1,..' – agstudy 2013-02-15 17:25:04

+1

@agstudy謝謝你的評論。我修改了我的答案。 – 2013-02-15 19:14:06

1

我會用split,然後cbind在一起,-填充後。我借用cbindPad功能從combining two data frames of different lengths

cbindPad <- function(...){ 
    args <- list(...) 
    n <- sapply(args,nrow) 
    mx <- max(n) 
    pad <- function(x, mx){ 
    if (nrow(x) < mx){ 
     nms <- colnames(x) 
     padTemp <- matrix(NA,mx - nrow(x), ncol(x)) 
     colnames(padTemp) <- nms 
     return(rbind(x,padTemp)) 
    } 
    else{ 
     return(x) 
    } 
    } 
    rs <- lapply(args,pad,mx) 
    return(do.call(cbind,rs)) 
} 

## assume your data is in a data.frame called dat 
dat_split <- split(dat, dat$Element1) 
out <- do.call(cbindPad, dat_split) 
+0

嗨CauchyDistributedRV!非常感謝!它工作得很好。我永遠無法寫出如此複雜的功能。非常感謝! – Fuv8 2013-02-15 17:08:32