使用查找 table 替换列名,如果查找 table 包含旧列名
Replace column names using lookup table, if lookup table contains old column name
我有一个如下所示的数据框:
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))
我还查找了 table 我想更改的旧列名称:
lookup <- data.frame(old = c("PLOT.ID", "Diameter"),
new = c("plot_id", "diam"))
如何使用查找 table 仅替换出现在 lookup$old
中的 test
中的列名,而让其他列保持原样?
到目前为止,我的方法删除了未出现在 lookup$old
中的列名称,并将其替换为空白:
test_new <- setNames(test, lookup$new[match(names(test), lookup$old)])
您可以使用 plyr
包中的 mapvalues
函数:
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
我有一个如下所示的数据框:
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))
我还查找了 table 我想更改的旧列名称:
lookup <- data.frame(old = c("PLOT.ID", "Diameter"),
new = c("plot_id", "diam"))
如何使用查找 table 仅替换出现在 lookup$old
中的 test
中的列名,而让其他列保持原样?
到目前为止,我的方法删除了未出现在 lookup$old
中的列名称,并将其替换为空白:
test_new <- setNames(test, lookup$new[match(names(test), lookup$old)])
您可以使用 plyr
包中的 mapvalues
函数:
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