首页 > 解决方案 > 我可以根据列表格式的查找表重命名 DF 吗?

问题描述

例子:

library(tidyverse)
names_lookup <- list(
  'mpg' = 'miles_per_gallon',
  'cyl' = 'cylinder'
)

我知道如何使用 dplyr::rename 手动重命名列

my_mtcars <- mtcars %>% rename(miles_per_gallon = mpg, cylinder = cyl)

我想知道,有没有办法可以使用我的列表“names_lookup”来重命名列?

标签: r

解决方案


在这里,我们需要在list

names_lookup <- list('miles_per_gallon' = 'mpg', 'cylinder' = 'cyl')

然后进行评估!!!

library(dplyr)
mtcars1 <- mtcars %>% 
       rename(!!! names_lookup)

-检查

names(mtcars1)
#[1] "miles_per_gallon" "cylinder"         "disp"             "hp"               "drat"             "wt"              
#[7] "qsec"             "vs"               "am"               "gear"             "carb"            names(mtcars)
#[1] "mpg"  "cyl"  "disp" "hp"   "drat" "wt"   "qsec" "vs"   "am"   "gear" "carb"

或者另一种选择是rename_at

mtcars %>% 
     rename_at(vars(unlist(names_lookup)), ~ names(names_lookup))

如果数据集中不存在某些列名,我们可以list根据值%in%的出现对列名进行子集化

names_lookup$hello <- 'Hello'
i1 <- unlist(names_lookup) %in% names(mtcars)
names_lookup_sub <- names_lookup[i1]

mtcars %>% 
 rename_at(vars(unlist(names_lookup_sub)), 
             ~ names(names_lookup_sub))

或与rename

mtcars1 <- mtcars %>% 
       rename(!!! names_lookup[i1])

推荐阅读