Change column name based on named vector (R)

Viewed 345

I have the following dataframe:

   a b c d e f g h i j
   1 1 1 1 1 1 1 1 1 1
   1 1 1 1 1 1 1 1 1 1
   1 1 1 1 1 1 1 1 1 1
   1 1 1 1 1 1 1 1 1 1

And the following vector (or dataframe)

sample     name
a          1
b          2
c          3
d          4
e          5
f          6
g          7
h          8
i          9
j          10

I want to rename the columns on the first dataframe, based on the second dataframe:

   1 2 3 4 5 6 7 8 9 10
   1 1 1 1 1 1 1 1 1 1
   1 1 1 1 1 1 1 1 1 1
   1 1 1 1 1 1 1 1 1 1
   1 1 1 1 1 1 1 1 1 1
1 Answers

We may use match

names(df1) <- df2$name[match(names(df1), df2$sample)]

-output

> df1
  1 2 3 4 5 6 7 8 9 10
1 1 1 1 1 1 1 1 1 1  1
2 1 1 1 1 1 1 1 1 1  1
3 1 1 1 1 1 1 1 1 1  1
4 1 1 1 1 1 1 1 1 1  1

Or use a named vector to match

names(df1) <- setNames(df2$name, df2$sample)[names(df1)]

data

df1 <- structure(list(a = c(1L, 1L, 1L, 1L), b = c(1L, 1L, 1L, 1L), 
    c = c(1L, 1L, 1L, 1L), d = c(1L, 1L, 1L, 1L), e = c(1L, 1L, 
    1L, 1L), f = c(1L, 1L, 1L, 1L), g = c(1L, 1L, 1L, 1L), h = c(1L, 
    1L, 1L, 1L), i = c(1L, 1L, 1L, 1L), j = c(1L, 1L, 1L, 1L)), 
class = "data.frame", row.names = c(NA, 
-4L))

df2 <- structure(list(sample = c("a", "b", "c", "d", "e", "f", "g", 
"h", "i", "j"), name = 1:10), class = "data.frame", row.names = c(NA, 
-10L))
Related