【问题标题】:Rename the same column in a list of identical data frames in r重命名r中相同数据框列表中的同一列
【发布时间】:2021-03-18 22:09:54
【问题描述】:

我对 R 还很陌生,我想知道是否有人可以帮助我?

我有一个相同数据帧(df1、df2、...、df9)的列表,我正在尝试将所有数据帧中的一列“value”重命名为“value_dataframename”-所有 9 个数据框中的重命名列应为 df1 中的 value_df1、df2 中的 value_df2、...、df9 中的 value_df9。

任何帮助将不胜感激!

【问题讨论】:

  • 您介意分享您(最新)尝试的代码 sn-p 吗?这可能是很好的学习,因为您实际上可能已经接近答案并且可能只需要一些调整
  • 到目前为止,我唯一能做的就是将这段代码重复 9 次并进行适当的更改,我知道这样做效率不高: 200% rename( Value_200 =价值)
  • 如果您觉得我的回答有用,请将其标记为“已解决”。谢谢!

标签: r loops rename


【解决方案1】:

试试这个:

## these two are my sample data frames for this example
df_1 <- data.frame(first = rbinom(10,size = 2,prob = 0.3), second = rnorm(10))
df_2 <- data.frame(first = rbinom(10,size = 2,prob = 0.3), second = rnorm(10))

# R stores data frames as list, so you can retrieve all your data frames thus:
all_df_names = ls.str(mode = "list")

# to check: all_df_names[1] - the first element - will give you "df_1", which is the name of the first data frame
# be careful though - 'ls.str(mode = "list")' will pick ALL the lists currently in your environment
# if you don't want to use this ls method, it might be wiser to manually create a variable 'all_df_names' and put all your data frame names there yourself.

# rename
for(i in 1:length(all_df_names)) {
  # get the actual content via its variable name, and store it in a temporary variable 'x'
  x = get(all_df_names[i])
  # rename the column you want
  names(x)[2] = paste0(names(x)[2], "_", i)   # this will replace the column with the previous name plus a '_' and the current iteration
  # resave that dataframe, with the new content
  assign(all_df_names[i], x)
}

# to remove variables we no longer need when done:
# rm(x, i)

# confirm
# names(df_1) = "first"    "second_1"
# names(df_2) = "first"    "second_2"

【讨论】:

  • 太棒了。如果这正是您想要的,请将其标记为已接受的答案(或者如果愿意,至少可以投票)。一切顺利。
【解决方案2】:

下面的代码示例列表 (auto.list) 可以满足您的需求。运行它来检查。 要将其用于您的列表:

  1. 跳过代码直到your.list &lt;- ...行,
  2. 将您的列表保存为your.list 对象,
  3. 分配给term你的“价值”。
auto.list <- list()

for (i in seq_len(10)) {
  auto.list[[i]] <- data.frame("a" = 1:i, "value" = sample(letters, i))
  names(auto.list)[i] <- paste0("df", i)
}
    
your.list <- auto.list # assign to your.list your own list
term <- "value" # assign your own "value"
   
for (i in seq_along(your.list)) {
  colnames(your.list[[i]])[colnames(your.list[[i]]) == term] <- paste0(term, "_", names(your.list)[i])
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2017-12-28
    • 1970-01-01
    相关资源
    最近更新 更多