Reputation:
Unable to solve this problem, i'm having with making an array in R. R displays an array error.
When you do mat2 <- array(1:12, dim=c(4,3)) mat2, R works and it displays the code, however when, I do: a <- array(8,1,2,5,9,2,9,1, dim=c(2,4), R doesn't work!
a <- array(8,2,9,9,1,5,2,1, dim=c(2,4))
a
Upvotes: 0
Views: 1419
Reputation: 173517
The first argument to array
should be a vector. In R you can create vectors with c()
. So you wanted:
a <- array(c(8,2,9,9,1,5,2,1), dim=c(2,4))
When you call a function like array
, each argument is separated by a comma (with some mild caveats in the case of special arguments like ...
). That means that when you write array(8,2,9,9,1,5,2,1, dim=c(2,4))
R doesn't see one set of numbers that should be taken together. It sees you trying to pass eight different arguments to the function array
, and it gets understandably confused.
In the case of 2D arrays, it is typically best to use matrix
instead, which includes a byrow
argument to control whether the data is filled by row or by column. Typically you would only use array
for multidimensional arrays where that distinction isn't as sensible. So it sounds like what you actually want in this case is:
matrix(c(8,2,9,9,1,5,2,1),nrow = 2,ncol = 4,byrow = TRUE)
Upvotes: 1