1

i tried Naming the Vector in R. a<-1:5 names(a[2])<-"e" #this is not showing any warning or error but Naming is not done

but

names(a)[2]<-"e" # this is is Naming the Element properly.

Kindly help with Explanation.

  • 1
    Similar to this: [https://stackoverflow.com/questions/38643000/naming-list-elements-in-r](https://stackoverflow.com/questions/38643000/naming-list-elements-in-r) – RobertMyles Nov 08 '17 at 17:36

1 Answers1

1

The basic difference is in understanding what a[1] and names(a)[1] stands for.

a<-1:5 (This assigns values 1 to 5 and creates a vector)

a[1] # This gives below output i.e the value stored at first location [1] 1

names(a)[1] # Shows the label associated with the value in this case 'NULL' yet

NULL

Now assigning the required name to the value

names(a)[2]<-"e"

This does the correct assignment and is how the R expects the code. You can then extract the value by element name namely

a["e"] #will give output 2

Rahul Pant
  • 707
  • 5
  • 7