r - 我可以根据列表格式的查找表重命名 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”来重命名列?
解决方案
在这里,我们需要在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])
推荐阅读
- angular - Angular 6如何检查我的管道过滤器是否返回一个空数组
- javascript - 在传递一些变量参数时,我如何正确使用 onclick() 方法,即在这种情况下的参数是 Mongoose 对象文档的 ID?
- python - 用熊猫读取excel文件
- node.js - 无法读取 csv 解析器中未定义的属性管道
- tomcat - 通过 JMX 监控单个主机上的多个 Tomcat JVM 的 Zabbix 配置
- python - 这个 Perl shebang 是如何工作的?(对于不是来自 Perl 的人)
- node.js - Mongo Aggregate - 根据日期计算
- azure - Azure 警报监视器条件始终保持不变
- ios - 在 iOS 13 上读取 Mifare Ultralight NFC 标签时出现“标签连接丢失”错误
- java - 将批量数据从一个数据库插入另一个数据库的最佳方法