Sarah
Sarah

Reputation: 37

Replacing an element within a vector in a list

I have a list of vectors that looks like

[[1]][1] 1 1 2

[[2]]
[1] 1 1 2

[[3]]
[1] 2 1 1

[[4]]
[1] 2 2 2

I would like the replace the first component of each of the vectors with a 9. I have tried

out <- append(vecs2T2[[1]], y, after=0)

but this just adds an 9 in at the start and does not replace it (see below).

[1] 9 1 1 2

I would like this entry to read 912.

Upvotes: 1

Views: 51

Answers (2)

Sotos
Sotos

Reputation: 51582

Another idea is to use Map and concatenate 9 with the each vector minus its first element

Map(function(x, y)c(x, y[-1]), 9, l1)

Upvotes: 0

iod
iod

Reputation: 7592

lapply(ll, replace, 1, 9)

This goes vector by vector, and replaces the 1st item with 9. (Replace's arguments are: (data, list-of-indexes, list-of-values), with the list of values recycled to be as long as the list of indexes.)

replace() is just defined as:

replace <- function (x, list, values) {
  x[list] <- values
  x
}

so you can also use that method.

lapply(ll, function(x) { x[1] <- 9 ; x })

You can use either with purrr::map(), too:

purrr::map(ll, ~{ .x[1] <- 9 ; .x })
purrr::map(ll, replace, 1, 9)

Head-to-head (not the best microbenchmark setup in the world tho):

microbenchmark::microbenchmark(
  purr_repl = purrr::map(ll, replace, 1, 9),
  purr_op = purrr::map(ll, ~{ .x[1] <- 9 ; .x }),
  lapp_repl = lapply(ll, replace, 1, 9),
  lapp_op = lapply(ll, function(x) { x[1] <- 9 ; x }),
  Map = Map(function(x, y)c(x, y[-1]), 9, ll)
)
## Unit: microseconds
##       expr    min      lq      mean  median      uq      max neval
##  purr_repl 27.510 29.7555  49.98242 31.4735 33.4805 1506.400   100
##    purr_op 84.415 86.9550 125.07364 90.0665 98.9465 2423.406   100
##  lapp_repl  4.422  4.8350   5.94472  5.1965  5.5930   34.947   100
##    lapp_op  4.672  5.4250  19.14590  5.9045  6.5015 1215.477   100
##        Map 10.670 12.2490  28.94712 13.5935 14.7170 1238.311   100

Upvotes: 1

Related Questions