2012-11-13 66 views
0

我想cbind不同向量的非多重长度。的那些更短将被(部分地)再循环作为香草cbindcbind任意长度向量无警告

cbind(c(1,2,3),c(4,5)) 
    [,1] [,2] 
[1,] 1 4 
[2,] 2 5 
[3,] 3 4 
Warning message: 
In cbind(c(1, 2, 3), c(4, 5)) : 
number of rows of result is not a multiple of vector length (arg 2) 

其结果是根据需要,除了警告。既然我想在扩展中使用它,是否有可能抑制警告或更好:谁知道直接解决方案产生相同的结果,没有警告! - 感谢,S.

回答

3

这里是一个选择,包装的关键概念到该安排的事情只是工作的功能。最简单的方法就是在...的每个元素上使用rep()...中的每个输入向量重复为公共长度(即最长输入向量的长度)。

这是我在下面使用rep()的参数length.out的参数。

CBIND <- function(..., deparse.level = 1) { 
    dots <- list(...) ## grab the objects passed in via ... this is a list 
    len <- sapply(dots, length) ## find lengths of individual vectors 
    ## this applies rep() over dots extending each component vector to length 
    ## of longest vector in ... 
    dots <- lapply(seq_along(dots), 
       function(i, x, len) rep(x[[i]], length.out = len), 
       x = dots, len = max(len)) 
    ## need to put everything together so arrange for a call to cbind 
    ## passing the extended list of vectors and passing along 
    ## the deparse.level argument of cbind 
    do.call(cbind, c(dots, deparse.level = deparse.level)) 
} 

这给:

R> CBIND(c(1,2,3),c(4,5)) 
    [,1] [,2] 
[1,] 1 4 
[2,] 2 5 
[3,] 3 4 
R> CBIND(c(1,2,3),c(4,5), deparse.level = 2) 
    c(1, 2, 3) c(4, 5, 4) 
[1,]   1   4 
[2,]   2   5 
[3,]   3   4 

我当然赞成这种过度简单重挫与suppressWarnings()警告呼叫缠。对于生产代码,您希望明确处理您想要允许的情况,并让警告在用户执行了您未考虑的事情的情况下传播。

+0

采取了点。如果事先检查传递给'cbind'的参数是否有其他问题,那么使用'suppressWarnings'的恕我直言仍然可以使用。 – BenBarnes

+0

如果用户传入的东西不是数字或数据框或...?你可能会用完整的测试来捕捉它们,但是你可能会错过一个咬你的用户,因为你没有想到它。我同意在这里可以合理使用'suppressWarnings()',但不能在生产代码中使用。 –

2

你可以使用suppressWarnings,如果你真的想:

suppressWarnings(cbind(c(1,2,3),c(4,5))) 
#  [,1] [,2] 
# [1,] 1 4 
# [2,] 2 5 
# [3,] 3 4 
+0

哦,很高兴知道!我问过这个问题,所以谢谢你,但是如果我正确地解释你的话......,如果你真的想要<部分的话,我可能会使用Gavins的解决方案。 – Janhoo

+0

@sunpyg,是的,你正确地解释我的措辞! – BenBarnes