Reputation: 155
I have a list containing three vectors, say:
test <- list(c(1,2,3,4),c(5,6,7),c(8,9,10))
I'd like to add elements to a given vector in the list. Let's say I'd like to add 11 to the last one (offset 3), so I'd have c(8,9,10,11) as the last element of the "test" list.
I tried:
test[3] <- c(test[3], 11)
test[[3]] <- c(test[1], 11)
test[3[length(test[3])] <- 11
append(test[3], 11)
And apparently nothing of the above works as I expect it to. How can I do this?
Upvotes: 3
Views: 86
Reputation: 9240
A purrr
option (corrected by Ritchie's comment):
test |> purrr::map_at(3, ~ c(.x, 11))
Upvotes: 1
Reputation: 78907
Extract one item with [[
The double square brackets are used to extract one element from potentially many. For vectors yield vectors with a single value; data frames give a column vector; for list, one element text from here
after this use c()
to concatenate:
test[[3]] <- c(test[[3]],11)
test[[3]]
[[1]]
[1] 1 2 3 4
[[2]]
[1] 5 6 7
[[3]]
[1] 8 9 10 11
Upvotes: 3