Keith John Hutchison Keith John Hutchison - 1 month ago 8
R Question

How to add a named element to a R list using a variable counter?

I have number of results to pass back to a calling procedure
I'd like to pass back a named list where each result is numbered.

# the following works
# result is a valid result
results = list( "1" = result)


When I do the following I end up with results$resultCounter instead of results$'1'

resultCounter = 1
results = list( resultCounter = result)


How do you pass in the contents of a variable to be the name of an element within a list?

Answer

One option would be to use setNames

results <- setNames(result, resultCounter)

data

result <- list(1:5, 6:10)
resultCounter <- 1:2