Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 925
Aserian Avatar asked Jul 27 '16 23:07

Aserian


1 Answers

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)]
like image 126
Hack-R Avatar answered Sep 18 '22 08:09

Hack-R