Issue with renaming data.table
Asked Answered
A

2

6

So I have the following data.table issue:

library(data.table)
dt1<-data.table(V1=runif(10),V2=sample(10),ID=1:10)
     dt1
                V1 V2 ID
     1: 0.26880759 10  1
     2: 0.59148373  9  2
     3: 0.15106101  8  3
     4: 0.64780998  5  4
     5: 0.09067745  7  5
     6: 0.57337100  2  6
     7: 0.17920313  3  7
     8: 0.87948063  4  8
     9: 0.25167438  1  9
    10: 0.82715461  6 10

and I am wishing to perform a column rename (except one column, namely the "ID").Although names(dt1[,-"ID"]) works OK yielding:

[1] "V1" "V2"

The following command fails:

   names(dt1[,-"ID"])<-c("souksou","mouksou")
   Error in -"ID" : invalid argument to unary operator

Of course the issue is bypassed via:

names(dt1)[!(names(dt1)  %in% "ID")]<-c("souksou","mouksou")

names(dt1)
[1] "souksou" "mouksou" "ID"

My question to the community is why this happens.

Acne answered 13/7, 2017 at 12:27 Comment(4)
you need to use setnames functionBenford
@Benford elaborate a bit...Acne
setnames(dt1, c("V1", "V2"), c("souksou","mouksou")). setnames is the way to rename columns by reference in a data.tableBenford
You can't set the names of a subset. You can only change a subset of the names.Amateurish
B
11

To put my comment into a more visible answer: in , the function setnames permits to rename columns (all of them or a subset of them) by reference.

Try ?setnames to see how it works. Basically, you need to give the function 3 arguments, x, old and new: x is your data.table, old are the names or the indices of the variables you want to rename (if you want to rename all of the variables, old can be the new names and you don't need to provide new) and new is the new column names.

In your example, you need to do:

setnames(dt1, c("V1", "V2"), c("souksou","mouksou"))
Benford answered 12/9, 2017 at 8:18 Comment(0)
A
2

I would suggest another way (and maybe a simpler one).

names(dt1) = gsub('V1', 'souksou', names(dt1))
names(dt1) = gsub('V2', 'mouksou', names(dt1))
Ascertain answered 31/1, 2022 at 12:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.