向矩阵错误添加新列 [英] Adding a new column to matrix error

查看:72
本文介绍了向矩阵错误添加新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向现有矩阵中添加新列,但每次都会收到警告.

I'm trying to add a new column to existing matrix, but getting warning everytime.

我正在尝试以下代码:

normDisMatrix$newColumn <- labels

获取此消息:

警告消息:在normDisMatrix $ newColumn<-标签中:强制LHS 到列表

Warning message: In normDisMatrix$newColumn <- labels : Coercing LHS to a list

在此之后,当我检查矩阵时,它似乎为空:

After it, when I check the matrix, it seems null:

dim(normDisMatrix)
NULL

注意:标签只是具有1到4之间数字的向量.

Note: labels are just vectors which have numbers between 1 and 4.

可能是什么问题?

推荐答案

正如@thelatemail指出的,$运算符不能用于对矩阵进行子集化.这是因为矩阵只是具有维度属性的单个向量.当您使用$尝试添加新列时,R将您的矩阵转换为可以在矢量(列表)上使用$的最低结构.

As @thelatemail pointed out, the $ operator cannot be used to subset a matrix. This is because a matrix is just a single vector with a dimension attribute. When you used $ to try to add a new column, R converted your matrix to the lowest structure where $ can be used on the vector, which is a list.

您想要的功能是cbind()( c 绑定).假设我有矩阵m

The function you want is cbind() (column bind). Suppose I have the matrix m

(m <- matrix(51:70, 4))
#      [,1] [,2] [,3] [,4] [,5]
# [1,]   51   55   59   63   67
# [2,]   52   56   60   64   68
# [3,]   53   57   61   65   69
# [4,]   54   58   62   66   70

要从名为labels的向量中添加新列,我们可以

To add the a new column from a vector called labels, we can do

labels <- 1:4
cbind(m, newColumn = labels)
#                     newColumn
# [1,] 51 55 59 63 67         1
# [2,] 52 56 60 64 68         2
# [3,] 53 57 61 65 69         3
# [4,] 54 58 62 66 70         4

这篇关于向矩阵错误添加新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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