8

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.

1
  • i want the list like in the first output with items named "itemx", but if an item is already named i want that name preserved. In the second result the list already had 1 named item "hello" and names for the first 2 werent filled in for some reason. Commented Jul 9, 2014 at 17:17

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.