Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何向向量添加数字标签_R_Tags - Fatal编程技术网

R 如何向向量添加数字标签

R 如何向向量添加数字标签,r,tags,R,Tags,我想知道如何在数据集中标记数字。为了举例说明,以下是我得到的: > U [,1] [1,] 5.019720 [2,] 3.849288 [3,] 3.434410 [4,] 3.418294 [5,] 3.723506 [6,] 3.108474 [7,] 2.534136 但我想要的是 1 2 3 4 5 5.019765 3.849315 3.434434 3.418317 3.723531 6

我想知道如何在数据集中标记数字。为了举例说明,以下是我得到的:

> U
     [,1]
[1,] 5.019720
[2,] 3.849288
[3,] 3.434410
[4,] 3.418294
[5,] 3.723506
[6,] 3.108474
[7,] 2.534136
但我想要的是

      1        2        3        4        5 
5.019765 3.849315 3.434434 3.418317 3.723531 
   6        7 
3.108500 2.534188 

似乎您想要构造一个命名向量。一种简单的方法是使用
setNames()


当然,这相当于:

names(x) <- 1:5
x
        1         2         3         4         5 
0.1350252 0.6986387 0.9814024 0.1204727 0.2901325 

names(x)Andrie打败了我,他的方法更优越,但这里有另一种方法(这展示了如何将矩阵对象[带维度]转化为向量):


U[,1]
您需要什么?输出必须与上面的输出相同。这两者都不能提供所需的输出。还要什么吗?谢谢你,安德烈。我就是这样after@Andrie,为什么
setNames()
而不仅仅是
names()
?(
names(x)@AnandaMahto你说得很对-这些都是等价的。我想这只是一种习惯。一旦我发现
setNames()
我发现我几乎一直在使用它,因为它节省了打字。
setNames(x, 1:5)
        1         2         3         4         5 
0.1350252 0.6986387 0.9814024 0.1204727 0.2901325 
names(x) <- 1:5
x
        1         2         3         4         5 
0.1350252 0.6986387 0.9814024 0.1204727 0.2901325 
U <- matrix(rnorm(6), ncol=1)
U2 <- c(U)
names(U2) <- 1:length(U2)
U2
        1         2         3         4         5         6 
-1.081053 -0.122568  1.650224 -2.217643  2.018205  1.451843