Aserian
Aserian

Reputation: 1117

How can I rename all columns of a data frame based on another data frame in R?

I am very new to R. I am trying to rename the columns of a data frame based on another dataframe.

Essentially My data looks like

DataFrame1

A    B    C   D
1    2    3   4

I have another table that looks like this' DataFrame2

Col1    Col2
A       E
B       Q
C       R
D       Z

I want to rename the columns of my first data frame based on this table so that it will come out:

E    Q    R    Z
1    2    3    4

I was trying a loop using the plyr library. This is the command I tried:

library(plyr)
for (i in names(DataFrame1[,3:336])) #renaming columns 3 to 336
    { 
        rename(DataFrame1,
         replace = c(i = DataFrame2[DataFrame2$Col1 == i, 2])) 
    }

My thinking was for each column in DataFrame1, rename the column with the lookup of the column in DataFrame2.

This produces N Rows of the error "The following from values were not present in x: i", where n is the number of rows present in DataFrame1

Thank you for any help you can offer!

Upvotes: 9

Views: 9146

Answers (3)

A5C1D2H2I1M1N2O1R2T1
A5C1D2H2I1M1N2O1R2T1

Reputation: 193517

I'd use setnames from "data.table" for this:

library(data.table)
# Might not work if your columns are factors, not characters
# setnames(dt1, dt2$Col1, dt2$Col2)[]

# Convert to character to use
setnames(dt1, as.character(dt2$Col1), as.character(dt2$Col2))[]
#   E Q R Z
# 1 1 2 3 4

If the data.frame containing the old and new names have more names than need to be replaced, you can add skip_absent=TRUE to setnames.

Upvotes: 0

Arun kumar mahesh
Arun kumar mahesh

Reputation: 2359

Simply you can rename the columns in base R

dt1 <- data.frame(A=1, B=2, C=3, D=4)

dt2 <- data.frame(Col1=c("A","B","C","D"),Col2=c("E","Q","R","Z"))

names(dt1) <- dt2$Col2

print(dt1)

E Q R Z
1 2 3 4

Replace and ifelse function may also rename the column names if data frames has same length

names(dt1) <- replace(names(dt1),!is.na(names(dt1)),dt2$Col2)
names(dt1) <- ifelse(!is.na(names(dt1)),dt2$Col2,NA)

print(dt1)

E Q R Z
1 2 3 4

Upvotes: 0

Hack-R
Hack-R

Reputation: 23200

A    B    C   D
1    2    3   4

DataFrame1 <- read.table(con <- file("clipboard"), header=T)

Col1    Col2
A       E
B       Q
C       R
D       Z

DataFrame2 <- read.table(con <- file("clipboard"), header=T)

colnames(DataFrame1) <- DataFrame2$Col2

If the column names didn't go in order like they do in the example you'd have to use match:

DataFrame2$Col2[match(names(DataFrame1),DataFrame2$Col1)]

Upvotes: 11

Related Questions