重命名R中的一个命名列 [英] Rename one named column in R

查看:204
本文介绍了重命名R中的一个命名列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想更新数据框架的一列,使用其原始名称来引用它,这是否可能?例如,我有表'data'

I want to update one column of a dataframe, referencing it using its original name, is this possible? For example say I had the table 'data'

a b c  
1 2 2  
3 2 3  
4 1 2

,我想将列b的名称更新为'd'。我知道我可以使用

and I wanted to update the name of column b to 'd'. I know I could use

colnames(data)[2] <- 'd'  

但我可以通过特别引用b来进行更改,例如

but can I make the change by specifically referencing b, i.e. something like

colnames(data)['b'] <- 'd'  

这样,如果数据框架的列顺序改变,正确的列名称仍会更新。

so that if the column ordering of the dataframe changes the correct column name will still be updated.

提前感谢

推荐答案

这看起来像是一个黑客,但第一件事是想到使用 grepl()足够详细的搜索字符串,只得到你想要的列。我确定有更好的选择:

This seems like a hack, but the first thing that came to mind was to use grepl() with a sufficiently detailed enough search string to only get the column you want. I'm sure there are better options:

dat <- data.frame(a = 1:3, b = 1:3, c = 1:3)
colnames(dat)[grepl("b", colnames(dat))] <- "foo"
dat
#------
  a foo c
1 1   1 1
2 2   2 2
3 3   3 3

正如Joran在下面指出的,我过于复杂的东西...不需要一个正则表达式。

As Joran points out below, I overcomplicated things...no need for a regex at all. This saves a few characters on the typing too.

colnames(dat)[colnames(dat) == "foo"] <- "bar"
#------
  a bar c
1 1   1 1
2 2   2 2
3 3   3 3

这篇关于重命名R中的一个命名列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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