Why there is no error when I give same name to two list elements in R

Viewed 57

I got this question while doing some practicals using R. So here is the scenario,

v = list(bob=c(2,3,5),bob=c("aa","bb"))

I have a list named v and there are two list elements both named as bob. When I compile this it does not give any error. But the most interesting factor is if I try to print bob using list name it gives me this result,

> v$bob
[1] 2 3 5

But if I print bob using attach() command it returns another way around.

> attach(v)
> bob
[1] "aa" "bb"
> detach(v)

These two different results made me curious and please can someone help to understand the underline theory.

1 Answers

With attach, it is overriding the first 'bob' i.e. 2, 3, 5 with the last entry. If we want to reverse it, use rev which just reverse the order of list elements and thus the first element of list will now be the last one

attach(rev(v))

-check

> bob
[1] 2 3 5

In general, it is recommended not to use attach.

If we want to create an object for a specific element use assign

assign(names(v)[1], v[[1]])

Regarding the question why there is no error in duplicate names of a list, it is a feature of list to have duplicate names as do matrix can have duplicate names. But, in data.frame, it is not allowed as there are functions in place to check for duplicates i.e. make.unique thus guaranteeing unique names

make.unique(c('bob', 'bob'))
[1] "bob"   "bob.1"

i.e. if we convert the list to a data.frame (after correcting for length i.e make the length same for the list elements - a data.frame is a list with equal length of its elements in addition to some more attributes)

data.frame(lapply(v, `length<-`, max(lengths(v))))
  bob bob.1
1   2    aa
2   3    bb
3   5  <NA>
Related