命名列重命名 [英] Named columns renaming

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

问题描述

我想重命名大型数据框的一些随机列,我想使用当前的列名,而不是索引。如果我添加或删除数据列,列索引可能会改变,所以我使用现有的列名是一个更稳定的解决方案。
这是我现在的:

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 merge 的结果。

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. 

尽管您最终可能要替换一个向量。在这种情况下,请使用%而不是 == 中的%,并将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天全站免登陆