与数据框绑定的中性元素

neutral element to cbind with dataframe

我可以做到以下几点:

a <- rep(5,5)

> cbind(6,a)
       a
[1,] 6 5
[2,] 6 5
[3,] 6 5
[4,] 6 5
[5,] 6 5
> cbind(NULL,a)
     a
[1,] 5
[2,] 5
[3,] 5
[4,] 5
[5,] 5

当我使用数据框执行此操作时,出现错误

> cbind(NULL,mtcars)

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

什么是中性元素使得:

cbind(neutralElement,DF) = DF 

编辑:

我有一段代码,其中的内容类似于 cbind(IDCOL,DF)。在函数中 IDCOL 也可以是非现有的,因此将 IDCOL 设置为中性元素会很方便,这样代码仍然可以顺利运行。

你要找的东西不太可能存在。

cbindrbind 命令的文档:

If there are several matrix arguments, they must all have the same number of columns (or rows) and this will be the number of columns (or rows) of the result. If all the arguments are vectors, the number of columns (rows) in the result is equal to the length of the longest vector. Values in shorter arguments are recycled to achieve this length (with a warning if they are recycled only fractionally). ... For cbind (rbind), vectors of zero length (including NULL) are ignored unless the result would have zero rows (columns), for S compatibility.

因此,我建议使用 if-else 条件:

if(length(IDCOL) > 0) {
   cbind(IDCOL, df) # make sure lengths are identical
} else {
   df # do whatever you want here
}