0

cbind複数の長さではない異なるベクトルを使用したいと思います。短いものはバニラのように(部分的に)リサイクルされますcbind

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。

4

2 に答える 2

3

これが1つのオプションであり、重要な概念を、物事が正常に機能するように調整する関数にラップします。最も簡単な方法はrep()、の各要素で使用して、各入力ベクトルを共通の長さ(つまり、最長の入力ベクトルの長さ)...に繰り返すことです。...

これは、のlength.out引数を使用して以下で行うことですrep()

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()。本番コードの場合、許可したいケースを明示的に処理し、ユーザーが説明していないことを行った状況で警告を伝播させたいと考えています。

于 2012-11-13T10:05:46.553 に答える
2

suppressWarnings本当に必要な場合は、を使用できます。

suppressWarnings(cbind(c(1,2,3),c(4,5)))
#      [,1] [,2]
# [1,]    1    4
# [2,]    2    5
# [3,]    3    4
于 2012-11-13T10:02:31.193 に答える