重命名由当前名称引用的多个数据框列 [英] Rename multiple dataframe columns, referenced by current names

查看:51
本文介绍了重命名由当前名称引用的多个数据框列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想重命名 large 数据框中的一些随机列,并且我想使用当前列名,而不是索引。如果我向数据中添加或删除列,则列索引可能会更改,因此我认为使用现有列名是更稳定的解决方案。
这就是我现在拥有的:

I want to rename some random columns of a large data frame and I want to use the current column names, not the indexes. Column indexes might change if I add or remove columns to the data, so I figure using the existing column names is a more stable solution. This is what I have now:

mydf = merge(df.1, df.2)
colnames(mydf)[which(colnames(mydf) == "MyName.1")] = "MyNewName"

我可以简化此代码,是原始的 merge()调用还是仅第二行? MyName.1 实际上是两个不同xts对象的xts 合并的结果。

Can I simplify this code, either the original merge() call or just the second line? "MyName.1" is actually the result of an xts merge of two different xts objects.

推荐答案

names(mydf)[names(mydf) == "MyName.1"] = "MyNewName" # 13 characters shorter. 

尽管,您最终可能希望替换向量。在这种情况下,请使用%in%代替 == 并将MyName.1设置为与MyNewName

Although, you may want to replace a vector eventually. In that case, use %in% instead of == and set MyName.1 as a vector of equal length to MyNewName

这篇关于重命名由当前名称引用的多个数据框列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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