替换列表中向量中的元素

时间:2018-11-21 14:23:54

标签: r

我有一个向量列表

[[1]][1] 1 1 2

[[2]]
[1] 1 1 2

[[3]]
[1] 2 1 1

[[4]]
[1] 2 2 2

我想用9替换每个向量的第一部分。我尝试过

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

,但这只是在开始处添加一个9,而不是替换它(请参见下文)。

[1] 9 1 1 2

我希望该条目阅读912

2 个答案:

答案 0 :(得分:1)

lapply(ll, replace, 1, 9)

这一步一步地进行,并且replace将第一个项加9。(替换的参数是:(数据,索引列表,值列表),值列表被回收到与索引列表一样长。)

replace()仅定义为:

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

因此您也可以使用该方法。

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

您也可以与purrr::map()一起使用:

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

一对一(不是世界上最好的微基准设置):

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

答案 1 :(得分:0)

另一个想法是使用Map并将9与每个向量减去其第一个元素相连

Map(function(x, y)c(x, y[-1]), 9, l1)
相关问题