oisyutat
oisyutat

Reputation: 197

Retain rownames as names of vector in R

I have a dataframe as follows:

> df <- data.frame("A"=rnorm(26), "B"=rnorm(26),row.names=sample(letters,26))

I then want to take column B out as a vector using a different row order

> newOrder <- sample(letters,26)
> vec <- df[newOrder,"B"] #1

How can I retain the correct rownames of df as the vector names of vec in a single statement at #1? That is, without having to do:

> names(vec) <- newOrder

Upvotes: 1

Views: 6200

Answers (1)

Dason
Dason

Reputation: 61933

You can set the names at the same time by using setNames

> vec <- setNames(df[newOrder, "B"], newOrder)
> vec
          q           c           a           l           g           v 
-0.44632045  0.80264068 -0.51574653 -1.57176346  0.16977483 -0.04916571 
          j           z           u           b           w           p 
 0.95736262 -0.35259227  0.20451454 -0.03873499  0.62497872  1.26984233 
          f           t           o           y           n           k 
 0.52851609 -0.37680593 -2.01770314 -0.94752793  0.64001006  1.72032405 
          d           e           m           r           s           i 
 0.30731069  0.54537837  2.32968848 -0.43577586 -0.16144602 -0.12817791 
          x           h 
 0.52822103  1.68236876 

Upvotes: 5

Related Questions