Add named vector to a list

This is horribly basic but I can't seem to figure it out

Suppose I have a list of variable entries:

lst <- list(a=1:4, b=rep('k', 5), c=3)

If I want to add a vector to this with a specified name I should be able to do so by:

c(f=1:5, lst)

But instead of creating an entry called 'f' containing 1 2 3 4 5 it creates five entries (f1 - f5) containing one of the numbers each.

How do I supress this behavior?

I know I can use

lst$f <- 1:5

but I would like to append the list within a function call...


Turn f into a list of one, and then concatenate it:

c(list(f=1:5), lst)

here is a simple function to append one (or more) item to a list:

lappend <- function (lst, ...){
lst <- c(lst, list(...))

> a <- list()
> a

> lappend(a,c(1,2,3))
[1] 1 2 3

> lappend(a, c(4,5,6), c(7,8,9))
[1] 4 5 6

[1] 7 8 9

Hope that helps!! Bye.

You can just do:

lst[[key]] <- any_object

(note the double square brackets [[]])

any_object can, of course, be a vector.

This method has the advantage of being usable even if the exact value of key is stored in a variable and you don't know it in advance, or if it's the variable being iterated in a for loop for example:

count <- list()
for (k in c("boys","girls","other")) {
  count[[k]] <- sum(data == k)

More versatile solution is with append:

append(lst, list(f=1:5), after=0)# after - position to append

Need Your Help

Ambiguous references with the exact same namespace

c# ef-code-first resharper

The RC class is not linked to a database, it is a simple class. The class is at only one place and is not partial. The Aérochem.Domain dll project compiles just fine.

How can I use an HTTP proxy for a JAX-WS request without setting a system-wide property?

java http soap proxy jax-ws

I have an application that needs to make a SOAP client request to a system on the Internet, so it needs to go though our HTTP proxy.