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

问题描述



说我有



有人应该已经问过了, pre> x = data.frame(q = 1,w = 2,e = 3,...和许多列...)

什么是最优雅的方式来重命名一个任意一列的列,我的位置我不一定知道,到其他任意名称? p>

例如假设我想将qe重命名为A code>和B,最优雅的代码是什么?



显然,我可以做一个循环

  oldnames = c(q,e)
newnames = c A,B)
for(i in 1:2)names(x)[names(x)== oldnames [i]] = newnames [i]

但我想知道是否有更好的方法?也许使用一些包? ( plyr :: rename 等)

解决方案

setnames data.table 包将在 data.frame data.table s

  library(data.table)
d< - data.frame(a = 1:2,b = 2:3,d = 4:5)
setnames(d,old = c('a','d'),new = c ('anew','dnew'))
d


#anew b dnew
#1 1 2 4
#2 2 3 5

请注意,更改是通过引用进行的,因此不会复制(即使是data.frames!)


Someone should have asked this already, but i couldn't find an answer.

Say I have

x=data.frame(q=1,w=2,e=3, ...and many many columns...)

what is the most elegant way to rename an arbitrary subset of columns, whose position I don't necessarily know, into some other arbitrary names?

e.g. Say I want to rename "q" and "e" into "A" and "B", what is the most elegant code to do this?

Obviously, I can do a loop

oldnames=c("q","e")
newnames=c("A","B")
for(i in 1:2)names(x)[names(x)==oldnames[i]]=newnames[i]

But I wonder if there is a better way? Maybe using some of the packages? (plyr::rename etc.)

解决方案

setnames from the data.tablepackage will work on data.frames or data.tables

library(data.table)
d <- data.frame(a=1:2,b=2:3,d=4:5)
setnames(d, old = c('a','d'), new = c('anew','dnew'))
d


 #   anew b dnew
 # 1    1 2    4
 # 2    2 3    5

Note that changes are made by reference, so no copying (even for data.frames!)

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

07-26 12:38