无需循环即可将向量转换为矩阵 [英] Convert Vector to Matrix without Recycling

查看:30
本文介绍了无需循环即可将向量转换为矩阵的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我将向量转换为元素太少而无法填充矩阵的矩阵时,向量的元素将被回收.有没有办法关闭回收或以其他方式用 NA 替换回收的元素?

When I convert a vector to a matrix that has too few elements to fill the matrix, then the elements of the vector are recycled. Is there any way to turn recycling off or otherwise replace the recycled elements with NA?

这是默认行为:

> 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]

我希望得到的矩阵为

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

推荐答案

您无法关闭回收,但您可以在形成矩阵之前对向量进行一些操作.我们可以根据矩阵的维度来扩展向量的长度.length<- 替换函数将用 NA 填充向量直到所需的长度.

You can't turn recycling off, but you can do some manipulations to the vector before you form the matrix. We can extend the length of the vector based on what the dimensions of the matrix will be. The length<- replacement function will pad the vector with NA up 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

这篇关于无需循环即可将向量转换为矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆