首页 > 解决方案 > Rename vector rownames

问题描述

Here is my replicating example.

data <- c(100:105)

As you can view the rownames are 1:6. Instead I would like to change the rownames to a column I have called "names" where

names <- c(0,10,20,30,40,50)

I tried

cbind(names,data)

but this results in rownames being 1:6, and then a column for names, and a column for data. I want to replace the rownames 1:6 with the column "names"

Desired output:

0   100
10  101
20  102
30  103
40  104
50  105

标签: rrowbase

解决方案


你可以这样做:

data <- data.frame(data)
row.names(data) <- names
data

结果:

   data
0   100
10  101
20  102
30  103
40  104
50  105

编辑:如果你想保留一个向量:

data <- c(100:105)
names <- c(0,10,20,30,40,50)
attr(data,'names') <- names
attributes(data)
$`names`
[1] "0"  "10" "20" "30" "40" "50"

推荐阅读