Siniyas
Siniyas

Reputation: 471

Naming list items via loop in R

I want to take a list, create a String vector of the names of the list items, filling in blanks with a generic name and then set the names vector as the names of the list.

My code works fine for list who dont have items with names in it. It however does nothing, when there are items with a name in it.

addNamesToList <- function(myList){
  listNames <- vector()
  for(i in 1:length(myList)){
    if(identical(names(myList[i]),NULL)){
      listNames <- c(listNames,paste("item",i,sep=""))
    }else{
      listNames <- c(listNames,names(myList[i]))
    }
  }
  names(myList) <- listNames
  return (myList)
}

result without named items

$item1
[1] 2 3 4

$item2
[1] "hey" "ho" 

result with named items

[[1]]
[1] 2 3 4

[[2]]
[1] "hey" "ho" 

$hello
[1] 2 3 4

Hope you can help.

Upvotes: 8

Views: 14450

Answers (1)

Rich Scriven
Rich Scriven

Reputation: 99371

It sounds like you want to insert names where there is not currently a name. If that's the case, I would suggest using direct assignment via names(x) <- value, instead of using a loop to fill in the blanks.

In the following example, lst creates a sample list of three elements, the second of which is not named. Notice that even if only one of the list element has a name, its names vector is a character vector the same length as lst.

( lst <- list(item1 = 1:5, 6:10, item3 = 11:15) )
# $item1
# [1] 1 2 3 4 5
#
# [[2]]
# [1]  6  7  8  9 10
#
# $item3
# [1] 11 12 13 14 15

names(lst)
# [1] "item1" ""      "item3"

We can insert a name into the empty name element with the following. This will also work with a vector, provided the right side vector is the same length as the left side vector.

names(lst)[2] <- "item2"
lst
# $item1
# [1] 1 2 3 4 5
#
# $item2
# [1]  6  7  8  9 10
#
# $item3
# [1] 11 12 13 14 15

For a longer list containing sporadic empty names, you can use

names(list)[!nzchar(names(list))] <- namesToAdd

nzchar basically means "non-zero character" and returns a logical, TRUE if the element is a non-zero length string.

Upvotes: 8

Related Questions