Scott Funkhouser
Scott Funkhouser

Reputation: 170

appending to multiple elements of a list in R

Suppose you have a list foo containing some elements.

foo <- list()
foo[1:3] <- "a"
foo
# [[1]]
# [1] "a"

# [[2]]
# [1] "a"

# [[3]]
# [1] "a"

I would like to efficiently grow the list by both appending to existing elements and adding additional elements. For example adding "b" to elements 2:5, as simply as possible, preferably using foo[2:5]<-.

Desired output

# [[1]]
# [1] "a"

# [[2]]
# [1] "a" "b"

# [[3]]
# [1] "a" "b"

# [[4]]
# [1] "b"

# [[5]]
# [1] "b"

Upvotes: 4

Views: 1388

Answers (1)

Zheyuan Li
Zheyuan Li

Reputation: 73295

Oh this indeed works:

foo[2:5] <- lapply(foo[2:5], c, "b")

The c is the concatenation function.

Upvotes: 6

Related Questions