Earthshaker
Earthshaker

Reputation: 599

Rename dataframe columns based on values in another dataframe in R

I have one data frame which has one column & two records in it.

DF1=

Name 
M_D
ABC123

I have another dataframe which has two columns. I need to rename second dataframe columns with two values in first data frame.

DF2=

   PQR  LMN
   111  345
   456  999

I want DF2 as below

   M_D  ABC123
   111  345
   456  999

Thanks

Upvotes: 0

Views: 4098

Answers (3)

MKR
MKR

Reputation: 20085

You can access values for column names for DF2 using $ or [[ operator on DF1. Since OP has mentioned that he doesn't even know the column names of DF1, an option could be as:

names(DF2) <- DF1[,1]
DF2
#  M_D ABC123
#1 111    345
#2 456    999

#OR
names(DF2) <- DF1[[1]]

#OR
names(DF2) <- DF1$Name

Note: names(DF2) <- DF1[1] will not work as DF1[1] is still of type data.frame and names<- expects a vector.

Data:

DF2 <- read.table(text = 
"PQR  LMN
111  345
456  999",
header = TRUE, stringsAsFactors = FALSE)

DF1 <- read.table(text = 
"Name 
M_D
ABC123",
header = TRUE, stringsAsFactors = FALSE)

Upvotes: 2

Roasty247
Roasty247

Reputation: 729

This will work if the length of DF1$Name is the same as the number of columns of DF2

colnames(DF2) <- DF1$Name

Upvotes: 0

wibeasley
wibeasley

Reputation: 5287

Based on your comment above, I recommend hardcoding it with something like dplyr::rename().

DF2 <- DF2 %>% 
  dplyr::rename(
    M_D       = PQR,
    ABC123    = LMN
  )

In my experience, you shouldn't really trust that collaborators will give you the same dataset structure each time. This will throw an error if they've changed the column names (this is good --you want to be alerted to the problem early in the pipeline). If they've change the column order, dplyr::rename() will handle it gracefully & correctly.

Consider additional defensive programming tools like checkmate or testit to verify the column characteristics match your expectations (e.g., the PQR/M_D column is an integer with values between 0 and 5).

Upvotes: 0

Related Questions