简体   繁体   English

他们是一种在 R 中重命名我的工作区中所有数据框列的方法吗

[英]Is their a way to rename the columns of all the dataframes in my workspace in R

I have been trying to find a way of renaming all the columns of each data frame in the workspace in R. They just need to have the same column names.我一直在尝试找到一种方法来重命名 R 中工作区中每个数据框的所有列。它们只需要具有相同的列名。 The code below is an example of two data frames (cars and trucks) that will have column names "1:10".下面的代码是列名为“1:10”的两个数据框(汽车和卡车)的示例。 However, I have about so many data frames and want to automatically do that.但是,我有这么多的数据框,并希望自动执行此操作。

names(cars) <- c(1:10)
names(trucks) <- c(1:10)

Thanks in advance!提前致谢!

Here is one way to do it.这是一种方法。 Below I just used mtcars as an example and had one vector in my global env to show you can ignore other objects.下面我只是以 mtcars 为例,在我的全局环境中有一个向量来显示你可以忽略其他对象。 First I create a list containing the names of the dfs in the global env.首先,我创建一个包含全局环境中 dfs 名称的列表。 Then I use lapply to set the names to 1 to the length of columns in the data.然后我使用 lapply 将名称设置为 1 到数据中列的长度。 I name the list the names of the original data.frames and use list2env to export the list to the global env.我将列表命名为原始 data.frames 的名称,并使用 list2env 将列表导出到全局 env。

edit based on @gregor suggestion根据@gregor 建议进行编辑

mt1 <- mtcars

mt2 <- mtcars

v1 <- 1

dfslist <-  Filter(mget(ls()), f = is.data.frame)

l1 <- lapply(1:length(dfslist),function(x){
   setNames(dfslist[[x]],1:ncol(dfslist[[x]]))
})

names(l1) <- names(dfslist)

list2env(l1, .GlobalEnv)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM