# Convert vector to matrix without reinstalling

When I transform a vector to a matrix that has too few elements to fill the matrix, the elements of the vector are reverted to their original state. Is there a way to turn recirculation or otherwise replace the recirculated NA items?

This is the default behavior:

```
> matrix(c(1,2,3,4,5,6,7,8,9,10,11),ncol=2,byrow=TRUE)
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
[4,] 7 8
[5,] 9 10
[6,] 11 1
Warning message:
In matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11), ncol = 2, byrow = TRUE) :
data length [11] is not a sub-multiple or multiple of the number of rows [6]
```

I would like the resulting matrix to be

```
[,1] [,2]
[1,] 1 2
[2,] 3 4
[3,] 5 6
[4,] 7 8
[5,] 9 10
[6,] 11 NA
```

+3

source to share

1 answer

You can't turn off recirculation, but before you form the matrix, you can do some vector manipulation. We can expand the length of the vector based on the size of the matrix. The replacement function `length<-`

will fit the vector s `NA`

to the desired length.

```
x <- 1:11
length(x) <- prod(dim(matrix(x, ncol = 2)))
## you will get a warning here unless suppressWarnings() is used
matrix(x, ncol = 2, byrow = TRUE)
# [,1] [,2]
# [1,] 1 2
# [2,] 3 4
# [3,] 5 6
# [4,] 7 8
# [5,] 9 10
# [6,] 11 NA
```

+6

source to share