John L. Godlee
John L. Godlee

Reputation: 601

Replace column names using lookup table, if lookup table contains old column name

I have a data frame that looks like this:

test <- data.frame("PLOT.ID" = c(1,2,3),
                "Diameter" = c(1,2,3),
                "tag_id" = c(1,2,3),
                "COL_NA" = c(1,2,3))

I also have a lookup table with the old column names that I want to change:

lookup <- data.frame(old = c("PLOT.ID", "Diameter"), 
                     new = c("plot_id", "diam"))

How can I use the lookup table to replace only the column names in test that appear in lookup$old and leave others as they are?

My method so far removed column names that don't appear in lookup$old and replaces them with blanks:

test_new <- setNames(test, lookup$new[match(names(test), lookup$old)])

Upvotes: 1

Views: 863

Answers (1)

Ape
Ape

Reputation: 1169

You could use the mapvalues function from the plyr package:

test_new <- test
colnames(test_new) <- plyr::mapvalues(colnames(test),
    as.character(lookup$old), 
    as.character(lookup$new))

> test_new
  plot_id diam tag_id COL_NA
1       1    1      1      1
2       2    2      2      2
3       3    3      3      3

Upvotes: 2

Related Questions