首页 文章

在新数据中转换拆分的data.frame . 帧

提问于
浏览
0

我有一个看起来像这样的data.frame:

Element1 Element2 Value 指数
a cf 0.14 1
ng 0.25 1
a ck 0.12 1
rt 0.59 1
a pl 0.05 1
b gh 0.02 2
呃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
ng 0.25 b er 0.91
a ck 0.12 b jk 0.87
rt 0.59 NA NA NA
a p 0.05 0.05 NA NA NA

等等...

我应用“拆分”功能根据“索引”列拆分初始data.frame但我不能根据需要在单个data.frame中转换拆分的data.frame(即data.frames列表),因为单个data.frames不相等 . 我试图申请(从一层包装)

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

从另一篇文章中,但返回一个像初始一样的data.frame .

有人可以帮我吗?

最好

F .

2 回答

  • 1

    这是一种方法:

    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
    
  • 2

    我会一起使用 split 然后 cbind ,填充后 . 我从combining two data frames of different lengths借用了 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 )
    

相关问题