`colnames<-`(`*tmp*`, value = `*vtmp*`) 中的错误:尝试在小于二维的对象上设置 'colnames'

Error in `colnames<-`(`*tmp*`, value = `*vtmp*`) : attempt to set 'colnames' on an object with less than two dimensions

我正在尝试重命名 df 的特定列名称。

为了执行此任务,我使用一个函数通过 for 循环执行替换。

这是我的代码:


## data ##

df <- structure(list( 
  A = c(1,2,3),
  B = c("Yes", "Yes", "No"),
  C = c("John", "James", "Maria"),
  D = c(45, 34, 23),
  E = c(712, 777, 888)),
  
  class = "data.frame",
  row.names = c(NA, -3L))

## setting atomic vectors for original/new names ##

original_df_names <- c("A", "B", "C")
new_df_names <- c("Order", "Answer", "Name")


## function to rename columns ##

rename_fun <- function(df, original_names, new_names){
  for(i in 1:seq_along(original_names)){
    for(j in 1:seq_along(new_names)){
      colnames(df)[which(names(df) == i)] <- j
    }
  }
}

## applying function ##

df <- mapply(df = df,
             original_names = original_df_names,
             new_names = new_df_names,
             rename_fun)

控制台输出:

Error in `colnames<-`(`*tmp*`, value = `*vtmp*`) : 
  attempt to set 'colnames' on an object with less than two dimensions

预期输出

names(df)
[1] "Order" "Answer" "Names" "D" "E"

还有其他方法吗?

我们可以利用rename_at

library(dplyr)
df <- df %>%
       rename_at(vars(all_of(original_df_names)), ~ new_df_names)