Sarang Sarang - 1 month ago 11
R Question

names function in R not working as expected

I have a vector named v as follows:

> v


Moe Larry Curly Harry Tevez Kagiso Harry Sierra


10 20 30 40 50 60 70 NA 110 NA 1110 1210


Now, I am trying to replace the empty names at v[9:12] with a 4 element vector, using :

names(v[9:12]) = c("A", "B", "C", "D")


The command runs OK, but when I print the vector v, the result is same as before.

Any suggestions, where am I wrong ?

Earlier when I had, v as below, it had worked OK.

> v
Moe Larry Curly Harry Tevez Kagiso

10 20 30 40 50 60 70 NA


I had used :

> names(v)[7:8] = c("Harry","Sierra")


> v
Moe Larry Curly Harry Tevez Kagiso Harry Sierra
10 20 30 40 50 60 70 NA

Answer

You are assigning names to the new vector 110, NA, 1110, 1210.

Try

names(v) <- c(names(v)[1:8], "A", "B", "C", "D")