user1994555
user1994555

Reputation: 103

rename columns of dataframe

I have one dataframe that basically looks like this (contains data):

t <- data.frame(x1 = 1:5, x2 = 1:5, stingsAsFactors = FALSE)

I have another dataframe that contains the original column names and a replacement for each

n <- data.frame(abb = c("x1", "x2"), erf = c("XX1", "XX2"), stringsAsFactors = FALSE)

What I would like to do is rename columns in dataframe t according to the specification in dataframe n. My problem is I can't figure out how to do that with map. Why is the following wrong:

map2_dfr(n$abb, n$erf, function(x, y) rename(t, !!y := x))

Upvotes: 2

Views: 197

Answers (2)

Sotos
Sotos

Reputation: 51602

Here is a one-liner in base R using match,

names(t) <- n$erf[match(names(t), n$abb)]
t
#  XX1 XX2
#1   1   1
#2   2   2
#3   3   3
#4   4   4
#5   5   5

Upvotes: 2

akrun
akrun

Reputation: 887951

We can use rename_at

library(dplyr)
t %>%
    rename_at(n$abb, ~ n$erf)

Upvotes: 2

Related Questions