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.)
To rename a column in R you can use the rename() function from dplyr. For example, if you want to rename the column “A” to “B”, again, you can run the following code: rename(dataframe, B = A) .
setnames
from the data.table
package will work on data.frame
s or 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
Note that changes are made by reference, so no copying (even for data.frames!)
With dplyr you would do:
library(dplyr)
df = data.frame(q = 1, w = 2, e = 3)
df %>% rename(A = q, B = e)
# A w B
#1 1 2 3
Or if you want to use vectors, as suggested by @Jelena-bioinf:
library(dplyr)
df = data.frame(q = 1, w = 2, e = 3)
oldnames = c("q","e")
newnames = c("A","B")
df %>% rename_at(vars(oldnames), ~ newnames)
# A w B
#1 1 2 3
L. D. Nicolas May suggested a change given rename_at
is being superseded by rename_with
:
df %>%
rename_with(~ newnames[which(oldnames == .x)], .cols = oldnames)
# A w B
#1 1 2 3
Another solution for dataframes which are not too large is (building on @thelatemail answer):
x <- data.frame(q=1,w=2,e=3)
> x
q w e
1 1 2 3
colnames(x) <- c("A","w","B")
> x
A w B
1 1 2 3
Alternatively, you can also use:
names(x) <- c("C","w","D")
> x
C w D
1 1 2 3
Furthermore, you can also rename a subset of the columnnames:
names(x)[2:3] <- c("E","F")
> x
C E F
1 1 2 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With