0

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

3
  • will you know the column names of either data.frame at design time? Or will both always be unknown/different? Commented May 11, 2018 at 21:15
  • As of now i know , but i think it might change in future as it is read from a monthly file , so if any dynamic approach will also be great , otherwise I can some how hard code it. Commented May 11, 2018 at 21:17
  • 1
    names(DF2) <- DF1$Name Commented May 11, 2018 at 21:26

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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).

Comments

0

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

colnames(DF2) <- DF1$Name

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.