Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

appending to multiple elements of a list in R

Tags:

list

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"
like image 337
Scott Funkhouser Avatar asked Oct 14 '25 14:10

Scott Funkhouser


1 Answers

Oh this indeed works:

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

The c is the concatenation function.

like image 83
Zheyuan Li Avatar answered Oct 18 '25 16:10

Zheyuan Li