24

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...

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
ThomasP85
  • 1,624
  • 2
  • 15
  • 26

4 Answers4

31

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

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

Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
16

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)
}
A.L
  • 10,259
  • 10
  • 67
  • 98
Guillaume Chérel
  • 1,478
  • 8
  • 17
14

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

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

> a <- list()
> a
list()

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

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

[[2]]
[1] 7 8 9

Hope that helps!! Bye.

Michele
  • 8,563
  • 6
  • 45
  • 72
8

More versatile solution is with append:

append(lst, list(f=1:5), after=0)# after - position to append
Wojciech Sobala
  • 7,431
  • 2
  • 21
  • 27