使用参考文件更改所有R列名称 [英] Change all R columns names using a reference file

查看:160
本文介绍了使用参考文件更改所有R列名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在 R 中重命名数据框中的列。但是,重命名具有循环引用。我想解决这个问题,无法避免循环引用。一种思考的方法是重命名列并将其移动到新的 dataframe ,因此避免了循环引用。但是,我无法这样做。

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 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是指图像

Mapping.col is referred to the image

推荐答案

您可以在同一ti处重命名多个列我,而无需移动存储在data.frame中的数据本身。如果您知道正确的顺序,则可以使用

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

如果顺序不同,则可以使用 match 首先将它们匹配到正确的位置:

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)]

顺便说一句,总是分配名称和其他属性通过某种分配。 setNames 返回一些仍需要分配的内容。

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

这篇关于使用参考文件更改所有R列名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆