Home > Software engineering >  How can I modify a vector inside a list?
How can I modify a vector inside a list?

Time:01-16

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?

CodePudding user response:

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

CodePudding user response:

a purrr option:

test |> purrr::map_if(function(x) any(x %in% c(8, 9, 10, 11)), ~append(.x,11))
  •  Tags:  
  • r
  • Related