将数据框与空数据框绑定-cbind.fill? [英] cbind a dataframe with an empty dataframe - cbind.fill?

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

问题描述

我想我正在寻找 rbind.fill (在Hadley的 plyr 包中)的类似物code> cbind 。我看了看,但是没有 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.

我想要做的是以下事情:

What I want to do is the following:

#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 最后删除虚拟对象即可。添加虚拟对象并运行上面的代码后,我得到

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,因为那样会意味着将在绑定之后创建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.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.

从此处编辑脚本: LINK

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆