r - 使用键重命名列表中的数据框
问题描述
我有一个数据框列表,许多列需要重命名。最好设置一个可用于重命名数据框的密钥。数据框中的变量可能存在也可能不存在。我一直在寻找是否有一个已经这样做但找不到任何东西的功能。以下示例显示了我正在尝试做的事情。
# This is a dummy list with dataframes that may contain common variables
data_list <- list(
dfx1 <- mtcars,
dfx2 <- mtcars %>% rename(`mpg.1` = mpg, `cyl2` = cyl),
dfx3 <- mtcars %>% rename(`mpg.11` = mpg),
dfx4 <- mtcars %>% select(-mpg)
)
# Setup a key; the key does not have to be in this format
mykey <- c(
mpg = c("mpg.1", "mpg.11"),
cyl = c("cyl2")
)
# Is there a function that I can use to rename based in this key
lapply(x, fun, mykey)
解决方案
你的意思是这样的吗?
library( data.table )
#sample data
dt1 <- data.table( x = 1, yy = 2 )
dt2 <- data.table( xx = 1, yy = 2 )
L <- list(dt1, dt2)
#actual code renaming columns from old >> new
lapply( L, function(x) setnames( x, old = c("xx", "yy"), new = c("x", "y"), skip_absent = TRUE ) )
# [[1]]
# x y
# 1: 1 2
#
# [[2]]
# x y
# 1: 1 2
推荐阅读
- batch-file - 尝试批量获取没有临时文件的变量
- c# - 使用从数组中选择信息
- c++ - 在 C++ 中设计混合结构?
- java - 如何找到总和等于 k 且时间复杂度最小的最长子集(幂集)的长度?
- javascript - 谷歌图表 - 如何居中注释
- python - 根据时间范围制作字符串
- php - PHP isset($_POST["Submit1"])) 不工作
- ruby - 我的程序出错了!!!!此操作没有渲染队列
- neo4j - Neo4j 异常:java.lang.NoClassDefFoundError:非托管扩展上的 org/neo4j/cypher/javacompat/ExecutionEngine
- google-analytics - GA:交易报告并未显示所有交易