2013-02-15 79 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