Reputation: 601
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
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