首页 > 解决方案 > 使用键重命名列表中的数据框

问题描述

我有一个数据框列表,许多列需要重命名。最好设置一个可用于重命名数据框的密钥。数据框中的变量可能存在也可能不存在。我一直在寻找是否有一个已经这样做但找不到任何东西的功能。以下示例显示了我正在尝试做的事情。

# 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)

标签: r

解决方案


你的意思是这样的吗?

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

推荐阅读