Search code examples
rfunctionloopsvectorizationargs

how to vectorize the args of a function in R?


I have a list in R and I'm trying to rename the list members from a character array. For instance:

mylist <- list(c('a','b','c'),c('d','e'),'f')
headers <- c('heading1','heading2','heading3')

And I can rename the list members like this:

names(mylist) <- c(headers[1],
                   headers[2],
                   headers[3])

But when my list is 100s of members long, this code is horrible to write. I've tried using a for-loop as well as vectorized notation but nothing works. Apologies for what is doubtless a duplicate question but I've searched a lot of false leads in trying to google it


Solution

  • You can use the paste function to create numbered headers sequentially in a for loop. Then use the above answer to assign the headers to names of the list.

    mylist <- list(c('a','b','c'),c('d','e'),'f')
    headers <- rep(NA, length(mylist))
    for (i in 1:length(mylist)){
      headers[i] <- paste("heading", i, sep = "")
    }
    names(mylist) <- headers