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))
)
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.
I am having some trouble thinking of the right way to approach this..
Any suggestions?
CodePudding user response:
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"