Christofer Bogaso
2024-Dec-10 16:36 UTC
[R] outer() is not working with my simple function
Hi, I have below code FN1 = function(x, y) 3 outer(1:9, 1:9, FN1) With above I get error as below Error in dim(robj) <- c(dX, dY) : dims [product 81] do not match the length of object [1] Could you please help to understand why is it failing? I am just expecting to get a matrix with all elements as 3
outer() expects a return value with the same length as that of x. You could change the code to rep(3, length(x)) Or if you don't want to change the code of the function, you could make a wrapper and use that instead: function (x, y) { v <- FN1(x, y) if (length(v) != 1) v else rep(v, length(x)) } On Tue, Dec 10, 2024, 11:37 Christofer Bogaso <bogaso.christofer at gmail.com> wrote:> Hi, > > I have below code > > FN1 = function(x, y) 3 > > outer(1:9, 1:9, FN1) > > With above I get error as below > > Error in dim(robj) <- c(dX, dY) : > > dims [product 81] do not match the length of object [1] > > Could you please help to understand why is it failing? I am just > expecting to get a matrix with all elements as 3 > > ______________________________________________ > R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide > https://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >[[alternative HTML version deleted]]
On 2024-12-10 11:36 a.m., Christofer Bogaso wrote:> Hi, > > I have below code > > FN1 = function(x, y) 3 > > outer(1:9, 1:9, FN1) > > With above I get error as below > > Error in dim(robj) <- c(dX, dY) : > > dims [product 81] do not match the length of object [1] > > Could you please help to understand why is it failing? I am just > expecting to get a matrix with all elements as 3The help page says this about the function: "It must be a vectorized function (or the name of one) expecting at least two arguments and returning a value with the same length as the first (and the second)." So your function could be FN1 <- function(x, y) rep_len(3, length(x)) and it would work. Duncan Murdoch