Monal
Monal

Reputation: 127

Change names() of a numeric vector from one variable to another based on other dataframe

I have a numeric vector like so:

S1 S2 S3 S4
.1 .5 .3 .9

where S1, S2... are names for .1... I also have another df with columns like so:

sub.id State
 S1    CA  
 S2    OR
 S2    OR
 S4    CA
 S3    CO

I want to replace the names from first vector with the equivalent variable based on the data frame.

Upvotes: 1

Views: 1140

Answers (1)

akrun
akrun

Reputation: 887971

Try

 names(v1) <- setNames(df$State, df$sub.id)[names(v1)]
 v1
 # CA  OR  CO  CA 
 #0.1 0.5 0.3 0.9 

Or

  names(v1) <- df$State[match(names(v1), df$sub.id)]

data

 v1 <- structure(c(0.1, 0.5, 0.3, 0.9), .Names = c("S1", "S2", "S3","S4"))

 df <- structure(list(sub.id = c("S1", "S2", "S2", "S4", "S3"),
  State = c("CA", 
 "OR", "OR", "CA", "CO")), .Names = c("sub.id", "State"), 
 class = "data.frame", row.names = c(NA, -5L))

Upvotes: 3

Related Questions