简体   繁体   中英

Incorrect value for combination in R

Using the combinat package in R, I get an incorrect answer for

dim(combn(9,9))[2]

I get NULL instead of 1

Am I using the package incorrectly ? Or is there a different package out there to solve this ?

"Am I using the package incorrectly ?"

No, you are not using the package incorrectly. As @joran points out, from the documentation for the simplify argument for combinat::combn (which has a default value of TRUE ), this behavior is expected:

If simplify is FALSE, returns a list; else returns a vector or an array.

So, in your example, since combinat::combn(9, 9) has only one result, a vector is returned, which doesn't have attributes like a matrix (eg dim ) .

"Or is there a different package out there to solve this ?"

Yes, simply using the utils package that comes as one of the standard libraries with R fixes this issue (same as combinat , the default value for simplify is TRUE ):

## with utils
dim(utils::combn(9,9))[2]
[1] 1

Again, from the docs for utils::combn we have (emphasis mine):

Scott Chasalow wrote the original in 1994 for S; R package combinat and documentation by Vince Carey stvjc@channing.harvard.edu; small changes by the R core team, notably to return an ARRAY in all cases of simplify = TRUE, eg, for combn(5,5).

Note that it says array (an array in R is a vector with additional attributes.. furthermore a two-dimensional array is simply a matrix) and does not mention a vector as they did with combinat .

And for thoroughness, here is what utils::combn says for the argument simplify :

logical indicating if the result should be simplified to an array (typically a matrix); if FALSE, the function returns a list. Note that when simplify = TRUE as by default, the dimension of the result is simply determined from FUN(1st combination) (for efficiency reasons). This will badly fail if FUN(u) is not of constant length.

Since we have only 1 combination from utils::combn(9, 9) , we obtain an array (ie a matrix) with 1 column and 9 rows, so calling dim()[2] returns 1 as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM