Omega1x
Omega1x

Reputation: 59

Why does not the 'outer' function work properly for some argument values in R?

When I run the R command:

 outer(37:42, 37:42, complex, 1)

I get an error

"Error in dim(robj) <- c(dX, dY) : dims [product 36] do not match the length of object [37]"

in my R session. But when I run

outer(36:42, 36:42, complex, 1) 

I have a valid matrix as a result. The problem persists for all values greater than 36. And there is no problem for all values less then 37.

Is this a bug?

My system: Microsoft R Open 3.4.4 / RStudio 1.1.447 / Ubuntu 16.04

Upvotes: 2

Views: 322

Answers (2)

Omega1x
Omega1x

Reputation: 59

The problem is in the 4th argument: it should be named:

outer(37:42, 37:42, complex, length.out = 1)

works fine!

Upvotes: 0

Florian
Florian

Reputation: 25385

More specifically, when running the function with arguments m:n, m:n it returns the error whenever n < (n - m + 1)^2 [citation needed]. Try for example outer(20:23, 20:23, complex, 1) and outer(20:24, 20:24, complex, 1), where the first will fail but the latter won't, because 24 < (24-20+1)^2. I suspect this has to do with the first argument of complex being length.out, which defines the length of the vector to return - not really an explanation, I know. So your first argument 37:42 is passed to the length.out parameter. This does not make a lot of sense so please correct me if I am wrong, but I think what you want to do is the following:

outer(37:42, 37:42, function(x,y) {complex(1, real = x, imaginary = y)})

Which outputs:

       [,1]   [,2]   [,3]   [,4]   [,5]   [,6]
[1,] 37+37i 37+38i 37+39i 37+40i 37+41i 37+42i
[2,] 38+37i 38+38i 38+39i 38+40i 38+41i 38+42i
[3,] 39+37i 39+38i 39+39i 39+40i 39+41i 39+42i
[4,] 40+37i 40+38i 40+39i 40+40i 40+41i 40+42i
[5,] 41+37i 41+38i 41+39i 41+40i 41+41i 41+42i
[6,] 42+37i 42+38i 42+39i 42+40i 42+41i 42+42i

Hope this helps.

Upvotes: 0

Related Questions