'Unable to initialise a matrix
I wanted to create a matrix in R so I typed this:
a<- matrix(c(1:5), nrow = 2, byrow = TRUE)
print(a)
But instead of it executing it gives the error:
Error in matrix(c(1:5), nrow = 2, byrow = TRUE) : unused arguments (c(1:5), nrow = 2, byrow = TRUE)
At first i thought I had gotten the syntax wrong but i pasted many examples from different sites but same issue.
Solution 1:[1]
I got the same output as Peace. The main problem is the number of entries in the matrix. There are 5 entries for 2 rows. As mentioned in the warning 5 is not a multiple of 2. So R uses the first entry, which is 1 in our case, again as the second-row third-column entry of the matrix.
a<- matrix(c(1:5), nrow = 2, byrow = TRUE)
#> Warning in matrix(c(1:5), nrow = 2, byrow = TRUE): data length [5] is not a sub-
#> multiple or multiple of the number of rows [2]
print(a)
#> [,1] [,2] [,3]
#> [1,] 1 2 3
#> [2,] 4 5 1
Created on 2022-01-26 by the reprex package (v2.0.1)
When you change the entries of the matrix as below, there is no problem:
a<- matrix(c(1:6), nrow = 2, byrow = TRUE)
print(a)
#> [,1] [,2] [,3]
#> [1,] 1 2 3
#> [2,] 4 5 6
Created on 2022-01-26 by the reprex package (v2.0.1)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Coskun |
