Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating unique object names for list entries

I have example data as follows:

listoflists=
    list( 
        list(a = c(1,'a',3,4) , b = c(5,'b',6,7) ), 
        list(a = c(1,'a',2,6) , b = c(5,'b',0,8) ), 
        list(d = c(1,'a',2,6) , b = c(5,'b',0,8) ),
        list(d = c(1,'a',2,3) , b = c(5,'b',0,8) , a = c(5,'b',0,8)),
        list(d = c(1,'a',1,1))
    )

enter image description here

I would like rename the names (such as a and b), (only) if they have already been used. For example by adding a number at the end.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I am having some trouble thinking of the right way to approach this..

Any suggestions?

>Solution :

Maybe there is a more elegant way but just going through the list and renaming items while keeping count of each name’s uses works fine:

# all used names
names.used <- unique(unlist(sapply(listoflists, names)))
# usage counter for each name
names.n <- setNames(rep(0, length(names.used)), names.used)

for (i in seq_along(listoflists)) {
  for (j in seq_along(listoflists[[i]])) {
    
    name.ij <- names(listoflists[[i]])[j]
    
    # rename second and further occurrences
    if (names.n[name.ij] > 0) {
      names(listoflists[[i]])[j] <- paste0(name.ij, names.n[name.ij])
    }
    
    # update counter
    names.n[name.ij] <- names.n[name.ij] + 1
  }
}
# [[1]]
# [[1]]$a
# [1] "1" "a" "3" "4"
# 
# [[1]]$b
# [1] "5" "b" "6" "7"
# 
# 
# [[2]]
# [[2]]$a1
# [1] "1" "a" "2" "6"
# 
# [[2]]$b1
# [1] "5" "b" "0" "8"
# 
# 
# [[3]]
# [[3]]$d
# [1] "1" "a" "2" "6"
# 
# [[3]]$b2
# [1] "5" "b" "0" "8"
# 
# 
# [[4]]
# [[4]]$d1
# [1] "1" "a" "2" "3"
# 
# [[4]]$b3
# [1] "5" "b" "0" "8"
# 
# [[4]]$a2
# [1] "5" "b" "0" "8"
# 
# 
# [[5]]
# [[5]]$d2
# [1] "1" "a" "1" "1"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading