Xu *_*ang 39 r dataframe cbind
我想我正在寻找rbind.fill
(在Hadley的plyr
包装中)的类比cbind
.我看了,但没有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
Run Code Online (Sandbox Code Playgroud)
可以理解,这会产生错误:
Error in data.frame(..., check.names = FALSE) :
arguments imply differing number of rows: 0, 1
Run Code Online (Sandbox Code Playgroud)
我目前的解决办法是更换线路return_df <- data.frame()
用return_df <- data.frame(dummy=1)
,然后代码工作.然后我从return_df
最后删除虚拟.添加假人并运行上面的代码后,我得到了
dummy a b l m
1 1 1 2 hi there 44
Run Code Online (Sandbox Code Playgroud)
然后我只需要摆脱假人,例如:
> return_df[,2:ncol(return_df)]
a b l m
1 1 2 hi there 44
Run Code Online (Sandbox Code Playgroud)
我确定我错过了一种更简单的方法.
编辑:我想我不是在寻找一个cbind.fill,因为这意味着在cbind之后会创建一个NA值,这不是我想要的.
Tyl*_*ker 46
这是一个cbind填充:
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)))))
}
Run Code Online (Sandbox Code Playgroud)
我们来试试吧:
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,])
Run Code Online (Sandbox Code Playgroud)
我想我是从某个地方偷走了这个.
从这里编辑STOLE:LINK
Max*_*Max 12
虽然,我认为Tyler的解决方案是直接的,也是最好的解决方案,我只是提供另一种方式,使用rbind.fill()
我们已有的方法.
require(plyr) # requires plyr for rbind.fill()
cbind.fill <- function(...) {
transpoted <- lapply(list(...),t)
transpoted_dataframe <- lapply(transpoted, as.data.frame)
return (data.frame(t(rbind.fill(transpoted_dataframe))))
}
Run Code Online (Sandbox Code Playgroud)
使用 rowr::cbind.fill
rowr::cbind.fill(df1,df2,fill = NA)
A B
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 NA 6
Run Code Online (Sandbox Code Playgroud)