Search code examples
rrowradix

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

Solution

  • You could do this:

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

    Result:

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

    EDIT: if you want to keep a vector:

    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"