Nathan
Nathan

Reputation: 350

Renaming a subset of names

Lets say I'm trying to rename a some of the variables in data frame.

>dat = data.frame(var1 = 1:10, var2 = letters[1:10], var3 = LETTERS[1:10])  
>names(dat[,1:2]) = c("VAR_1", "VAR_2")  
>names(dat)

returns

>[1] "var1" "var2" "var3  

while

>names(dat)[1:2] = c("VAR_1", "VAR_2") 
>name(dat)

successfully renames the columns.

> [1] "VAR_1" "VAR_2" "var3"

Why is it that the second method works, but the first one fails?

Upvotes: 1

Views: 95

Answers (1)

James
James

Reputation: 66874

dat[,1:2] is a subsetted copy of dat, not the original. So you modify the names of this copy in the first example, and the copy is immediately discarded, with the original being unchanged.

Upvotes: 4

Related Questions