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.frameを分割するために「split」関数を適用しましたが、単一のデータの長さのため、分割されたdata.frame(つまりdata.framesのリスト)を必要に応じて単一に変換できません.framesは等しくありません。(プライパッケージから)応募してみました

x = do.call(rbind.fill、spl)

別の投稿と同じですが、最初の投稿のようなdata.frameが返されます。

4

2 に答える 2

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
于 2013-02-15T17:18:08.803 に答える
1

私はそれらを一緒に使用splitcbind、後パディングします。長さの異なる 2 つのデータ フレームを組み合わせcbindPadて関数を借ります。

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 )
于 2013-02-15T16:59:29.017 に答える