本文介绍了cbind 一个带有空数据框的数据框 - cbind.fill?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我正在为 cbind 寻找 rbind.fill(在 Hadley 的 plyr 包中)的类似物.我看了看,没有cbind.fill.

I think I'm looking for an analog of rbind.fill (in Hadley's plyr package) for cbind. I looked, but there is no cbind.fill.

我想做的是:

#set these just for this example
one_option <- TRUE
diff_option <- TRUE

return_df <- data.frame()

if (one_option) {
    #do a bunch of calculations, produce a data.frame, for simplicity the following small_df
    small_df <- data.frame(a=1, b=2)
    return_df <- cbind(return_df,small_df)
}

if (diff_option) {
    #do a bunch of calculations, produce a data.frame, for simplicity the following small2_df
    small2_df <- data.frame(l="hi there", m=44)
    return_df <- cbind(return_df,small2_df)
}

return_df

可以理解,这会产生错误:

Understandably, this produces an error:

Error in data.frame(..., check.names = FALSE) : 
arguments imply differing number of rows: 0, 1

我当前的解决方法是将 return_df <- data.frame() 替换为 return_df <- data.frame(dummy=1) 然后代码有效.然后我从最后的 return_df 中删除 dummy.添加虚拟对象并运行上述代码后,我得到

My current fix is to replace the line return_df <- data.frame() with return_df <- data.frame(dummy=1) and then the code works. I then just remove dummy from the return_df at the end. After adding the dummy and running the above code, I get

      dummy a b        l  m
1     1 1 2 hi there 44

然后我只需要摆脱假人,例如:

I then just need to get rid of the dummy, e.g.:

> return_df[,2:ncol(return_df)]
  a b        l  m
1 1 2 hi there 44

我确定我缺少一种更简单的方法来做到这一点.

I'm sure I'm missing an easier way to do this.

我想我不是在寻找 cbind.fill,因为这意味着将在 cbind 之后创建一个 NA 值,这不是我想要的.

edit: I guess I'm not looking for a cbind.fill because that would mean that an NA value would be created after the cbind, which is not what I want.

推荐答案

这是一个 cbind 填充:

Here's a cbind fill:

cbind.fill <- function(...){
    nm <- list(...) 
    nm <- lapply(nm, as.matrix)
    n <- max(sapply(nm, nrow)) 
    do.call(cbind, lapply(nm, function (x) 
        rbind(x, matrix(, n-nrow(x), ncol(x))))) 
}

让我们试试吧:

x<-matrix(1:10,5,2)
y<-matrix(1:16, 4,4)
z<-matrix(1:12, 2,6)

cbind.fill(x,y)
cbind.fill(x,y,z)
cbind.fill(mtcars, mtcars[1:10,])

我想我是从某个地方偷来的.

I think I stole this from somewhere.

从这里编辑 STOLE:链接

EDIT STOLE FROM HERE: LINK

这篇关于cbind 一个带有空数据框的数据框 - cbind.fill?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 05:42