Bruce Wayne
Bruce Wayne

Reputation: 491

Change all R columns names using a reference file

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:

enter image description here

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

Upvotes: 1

Views: 1690

Answers (1)

Emil Bode
Emil Bode

Reputation: 1830

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.

Upvotes: 1

Related Questions