Reputation: 21
While working with xml data (bibliographical), I transformed the tags into a list via xmlToList command. The problem is that there are multiple elements with the same tag that show up as list elements with identical names, say, a coauthored piece would have two identical tags, which become two identical list object names like $rec$stuff$record$author. For example:
Suppose the list is called A1:
$`rec`$`header`$`controlInfo`$artinfo$aug$au
# [1] "Smith, Bob"
$`rec`$`header`$`controlInfo`$artinfo$aug$au
# [1] "Jones, Mike"
A1$`rec`$`header`$`controlInfo`$artinfo$aug$au
is always "Smith, Bob."
I can't seem to find an obvious way to refer to the second entry, "Jones, Mike" without renaming the list elements (for other reasons other than parsing the data, I'd rather not). Plus, I'd need to be able to assign NA's to the second spot if there is no second element with the same name if possible. Is there a way to do this?
Thanks in advance!
Upvotes: 2
Views: 376
Reputation: 388982
Ideally names should be unique to avoid this exact problem. However, if you have similar names you can get all the elements with similar names by comparing the names with ==
.
Consider this example where name a1
is repeated
lst <- list(a = list(a1 = 1, a1 = 2, b1 = 1))
lst
#$a
#$a$a1
#[1] 1
#$a$a1
#[1] 2
#$a$b1
#[1] 1
lst$a$a1
would return only the first entry of a1
, to get all the elements with same name (a1
) we can compare the names
lst$a[names(lst$a) == "a1"]
#$a1
#[1] 1
#$a1
#[1] 2
and now let's say we want to change second a1
to 20 we can then do
lst$a[names(lst$a) == "a1"][[2]] <- 20
#$a
#$a$a1
#[1] 1
#$a$a1
#[1] 20
#$a$b1
#[1] 1
Upvotes: 1
Reputation: 10841
You can index a list in R using double brackets (see How to index an element of a list object in R). Try this:
> rec = list()
> rec
list()
> rec$x = "first"
> rec
$x
[1] "first"
> rec2 = c(rec,rec)
> rec2
$x
[1] "first"
$x
[1] "first"
> rec2$x = "second"
> rec2
$x
[1] "second"
$x
[1] "first"
> rec2[[1]]
[1] "second"
> rec2[[2]]
[1] "first"
> rec2[[2]] = "third"
> rec2
$x
[1] "second"
$x
[1] "third"
Upvotes: 2