Change all R columns names using a reference file

此生再无相见时 提交于 2019-12-11 06:05:47

问题


I am trying to rename columns in a dataframe in R. However, the renaming has circular referencing. I would like a solution to this problem, the circular referencing cannot be avoided. One way to think was to rename a column and move it to a new dataframe, hence, avoiding the circular referencing. However, I am unable to do so.

The renaming reference is as follows:

The current function I am using is as follows:

standard_mapping <- function(mapping.col, current_name, standard_name, data){
  for(i in 1:nrow(mapping.col)) {
    # i =32
    print(i)
    eval(parse(text = paste0("std.name = mapping.col[",i,",'",new_name,"']")))
    eval(parse(text = paste0("data.name = mapping.col[",i,",'",old_name,"']")))

    if(data.name %in% colnames(data)){
      setnames(data, old=c(data.name), new = c(std.name))
    }
  }
  return(data)
}

Mapping.col is referred to the image


回答1:


You can rename multiple colums at the same time, and there's no need to move the data itself that's stored in your data.frame. If you know the right order, you can just use

names(data) <- mapping.col$new_name

If the order is different, you can use match to first match them to the right positions:

names(data) <- mapping.col$new_name[match(names(data), mapping.col$old_name)]

By the way, assigning names and other attributes is always done by some sort of assignment. The setNames returns something, that still needs assigning.



来源:https://stackoverflow.com/questions/53714977/change-all-r-columns-names-using-a-reference-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!