199

有没有办法在我的 lapply() 函数中获取列表索引名称?

n = names(mylist)
lapply(mylist, function(list.elem) { cat("What is the name of this list element?\n" })

我之前问是否可以在 lapply()返回的列表中保留索引名称,但我仍然不知道是否有一种简单的方法可以在自定义函数中获取每个元素名称。我想避免在名称本身上调用 lapply,我宁愿在函数参数中获取名称。

4

12 回答 12

192

不幸的是,lapply它只给你传递它的向量的元素。通常的解决方法是将向量的名称或索引而不是向量本身传递给它。

但请注意,您始终可以向函数传递额外的参数,因此以下方法有效:

x <- list(a=11,b=12,c=13) # Changed to list to address concerns in commments
lapply(seq_along(x), function(y, n, i) { paste(n[[i]], y[[i]]) }, y=x, n=names(x))

在这里,我使用lapply了 的索引x,但也传入了x的名称x。如您所见,函数参数的顺序可以是任何东西 -lapply将“元素”(此处为索引)传递给额外参数中未指定的第一个参数。在这种情况下,我指定yand n,所以只剩i下...

产生以下内容:

[[1]]
[1] "a 11"

[[2]]
[1] "b 12"

[[3]]
[1] "c 13"

更新更简单的例子,同样的结果:

lapply(seq_along(x), function(i) paste(names(x)[[i]], x[[i]]))

这里函数使用“全局”变量x并在每次调用中提取名称。

于 2012-03-30T20:47:22.343 回答
57

这基本上使用与 Tommy 相同的解决方法,但使用Map(),无需访问存储列表组件名称的全局变量。

> x <- list(a=11, b=12, c=13)
> Map(function(x, i) paste(i, x), x, names(x))
$a
[1] "a 11"

$b
[1] "b 12"

$c
[1] "c 13

或者,如果您愿意mapply()

> mapply(function(x, i) paste(i, x), x, names(x))
     a      b      c 
"a 11" "b 12" "c 13"
于 2013-12-12T14:48:43.270 回答
42

R 版本 3.2 的更新

免责声明:这是一个 hacky 技巧,可能会在下一个版本中停止工作。

您可以使用以下方法获取索引:

> lapply(list(a=10,b=20), function(x){parent.frame()$i[]})
$a
[1] 1

$b
[1] 2

注意:这[]是工作所必需的,因为它欺骗 R 认为符号i(位于 的评估框架中lapply)可能有更多引用,从而激活它的惰性复制。没有它,R 将不会保留分开的副本i

> lapply(list(a=10,b=20), function(x){parent.frame()$i})
$a
[1] 2

$b
[1] 2

可以使用其他奇特的技巧,例如function(x){parent.frame()$i+0}function(x){--parent.frame()$i}

性能影响

强制复制会导致性能损失吗?是的!以下是基准:

> x <- as.list(seq_len(1e6))

> system.time( y <- lapply(x, function(x){parent.frame()$i[]}) )
user system elapsed
2.38 0.00 2.37
> system.time( y <- lapply(x, function(x){parent.frame()$i[]}) )
user system elapsed
2.45 0.00 2.45
> system.time( y <- lapply(x, function(x){parent.frame()$i[]}) )
user system elapsed
2.41 0.00 2.41
> y[[2]]
[1] 2

> system.time( y <- lapply(x, function(x){parent.frame()$i}) )
user system elapsed
1.92 0.00 1.93
> system.time( y <- lapply(x, function(x){parent.frame()$i}) )
user system elapsed
2.07 0.00 2.09
> system.time( y <- lapply(x, function(x){parent.frame()$i}) )
user system elapsed
1.89 0.00 1.89
> y[[2]]
[1] 1000000

结论

这个答案只是表明你不应该使用它......如果你找到像上面 Tommy 那样的另一个解决方案,你的代码不仅会更易读,而且与未来的版本更兼容,你还有失去核心团队努力的优化的风险开发!


旧版本的技巧,不再有效:

> lapply(list(a=10,b=10,c=10), function(x)substitute(x)[[3]])

结果:

$a
[1] 1

$b
[1] 2

$c
[1] 3

解释:lapply创建表单等的调用FUN(X[[1L]], ...)FUN(X[[2L]], ...)所以它传递的参数是循环中的当前索引在X[[i]]哪里。i如果我们在计算之前得到它(即,如果我们使用substitute),我们得到未计算的表达式X[[i]]。这是对[[函数的调用,带有参数X(一个符号)和i(一个整数)。所以substitute(x)[[3]]精确地返回这个整数。

有了索引,您可以轻松地访问名称,如果您先像这样保存它:

L <- list(a=10,b=10,c=10)
n <- names(L)
lapply(L, function(x)n[substitute(x)[[3]]])

结果:

$a
[1] "a"

$b
[1] "b"

$c
[1] "c"

或者使用第二个技巧::-)

lapply(list(a=10,b=10,c=10), function(x)names(eval(sys.call(1)[[2]]))[substitute(x)[[3]]])

(结果是一样的)。

解释 2:sys.call(1)返回lapply(...),所以这sys.call(1)[[2]]是用作列表参数的表达式lapply。传递这个来eval创建一个names可以访问的合法对象。棘手,但它的工作原理。

奖励:获取名称的第二种方法:

lapply(list(a=10,b=10,c=10), function(x)eval.parent(quote(names(X)))[substitute(x)[[3]]])

请注意,它X是 的父框架中的一个有效对象FUN,并且引用了 的列表参数lapply,因此我们可以使用 来获取它eval.parent

于 2013-08-29T14:39:09.877 回答
22

我已经多次遇到同样的问题......我已经开始使用另一种方式......lapply我没有使用,而是开始使用mapply

n = names(mylist)
mapply(function(list.elem, names) { }, list.elem = mylist, names = n)
于 2015-04-23T20:46:17.540 回答
14

您可以尝试使用imap()from purrrpackage。

从文档中:

如果 x 有名称,imap(x, ...) 是 map2(x, names(x), ...) 的简写,如果没有名称,则表示 map2(x, seq_along(x), ...)。

所以,你可以这样使用它:

library(purrr)
myList <- list(a=11,b=12,c=13) 
imap(myList, function(x, y) paste(x, y))

这将为您提供以下结果:

$a
[1] "11 a"

$b
[1] "12 b"

$c
[1] "13 c"
于 2017-11-07T19:50:06.773 回答
11

只需循环输入名称。

sapply(names(mylist), function(n) { 
    doSomething(mylist[[n]])
    cat(n, '\n')
}
于 2016-01-15T18:28:16.330 回答
5

汤米的回答适用于命名向量,但我知道你对列表感兴趣。似乎他正在做一个结束,因为他从调用环境中引用了“x”。此函数仅使用传递给函数的参数,因此不对传递的对象名称做任何假设:

x <- list(a=11,b=12,c=13)
lapply(x, function(z) { attributes(deparse(substitute(z)))$names  } )
#--------
$a
NULL

$b
NULL

$c
NULL
#--------
 names( lapply(x, function(z) { attributes(deparse(substitute(z)))$names  } ))
#[1] "a" "b" "c"
 what_is_my_name <- function(ZZZ) return(deparse(substitute(ZZZ)))
 what_is_my_name(X)
#[1] "X"
what_is_my_name(ZZZ=this)
#[1] "this"
 exists("this")
#[1] FALSE
于 2012-03-30T21:39:01.617 回答
4

我的答案与汤米和狞猫的方向相同,但避免了将列表另存为附加对象。

lapply(seq(3), function(i, y=list(a=14,b=15,c=16)) { paste(names(y)[[i]], y[[i]]) })

结果:

[[1]]
[1] "a 14"

[[2]]
[1] "b 15"

[[3]]
[1] "c 16"

这将列表作为命名参数提供给 FUN(而不是 lapply)。lapply 只需要遍历列表的元素(在更改列表长度时小心将第一个参数更改为 lapply)。

注意:将列表直接提供给 lapply 作为附加参数也可以:

lapply(seq(3), function(i, y) { paste(names(y)[[i]], y[[i]]) }, y=list(a=14,b=15,c=16))
于 2014-11-04T09:41:06.073 回答
3

@caracals 和 @Tommy 都是很好的解决方案,这是一个包括list´s 和data.frame´s 的示例。
r是´s 和list´s (在结尾处)。 listdata.framedput(r[[1]]

names(r)
[1] "todos"  "random"
r[[1]][1]
$F0
$F0$rst1
   algo  rst  prec  rorac prPo pos
1  Mean 56.4 0.450 25.872 91.2 239
6  gbm1 41.8 0.438 22.595 77.4 239
4  GAM2 37.2 0.512 43.256 50.0 172
7  gbm2 36.8 0.422 18.039 85.4 239
11 ran2 35.0 0.442 23.810 61.5 239
2  nai1 29.8 0.544 52.281 33.1 172
5  GAM3 28.8 0.403 12.743 94.6 239
3  GAM1 21.8 0.405 13.374 68.2 239
10 ran1 19.4 0.406 13.566 59.8 239
9  svm2 14.0 0.385  7.692 76.2 239
8  svm1  0.8 0.359  0.471 71.1 239

$F0$rst5
   algo  rst  prec  rorac prPo pos
1  Mean 52.4 0.441 23.604 92.9 239
7  gbm2 46.4 0.440 23.200 83.7 239
6  gbm1 31.2 0.416 16.421 79.5 239
5  GAM3 28.8 0.403 12.743 94.6 239
4  GAM2 28.2 0.481 34.815 47.1 172
11 ran2 26.6 0.422 18.095 61.5 239
2  nai1 23.6 0.519 45.385 30.2 172
3  GAM1 20.6 0.398 11.381 75.7 239
9  svm2 14.4 0.386  8.182 73.6 239
10 ran1 14.0 0.390  9.091 64.4 239
8  svm1  6.2 0.370  3.584 72.4 239

目标是unlist所有列表,将list's 名称的序列作为列来识别案例。

r=unlist(unlist(r,F),F)
names(r)
[1] "todos.F0.rst1"  "todos.F0.rst5"  "todos.T0.rst1"  "todos.T0.rst5"  "random.F0.rst1" "random.F0.rst5"
[7] "random.T0.rst1" "random.T0.rst5"

取消列出列表,但不列出data.frame´s。

ra=Reduce(rbind,Map(function(x,y) cbind(case=x,y),names(r),r))

Map将名称序列作为一列。Reduce加入所有data.frame的。

head(ra)
            case algo  rst  prec  rorac prPo pos
1  todos.F0.rst1 Mean 56.4 0.450 25.872 91.2 239
6  todos.F0.rst1 gbm1 41.8 0.438 22.595 77.4 239
4  todos.F0.rst1 GAM2 37.2 0.512 43.256 50.0 172
7  todos.F0.rst1 gbm2 36.8 0.422 18.039 85.4 239
11 todos.F0.rst1 ran2 35.0 0.442 23.810 61.5 239
2  todos.F0.rst1 nai1 29.8 0.544 52.281 33.1 172

PS r[[1]]

    structure(list(F0 = structure(list(rst1 = structure(list(algo = c("Mean", 
    "gbm1", "GAM2", "gbm2", "ran2", "nai1", "GAM3", "GAM1", "ran1", 
    "svm2", "svm1"), rst = c(56.4, 41.8, 37.2, 36.8, 35, 29.8, 28.8, 
    21.8, 19.4, 14, 0.8), prec = c(0.45, 0.438, 0.512, 0.422, 0.442, 
    0.544, 0.403, 0.405, 0.406, 0.385, 0.359), rorac = c(25.872, 
    22.595, 43.256, 18.039, 23.81, 52.281, 12.743, 13.374, 13.566, 
    7.692, 0.471), prPo = c(91.2, 77.4, 50, 85.4, 61.5, 33.1, 94.6, 
    68.2, 59.8, 76.2, 71.1), pos = c(239L, 239L, 172L, 239L, 239L, 
    172L, 239L, 239L, 239L, 239L, 239L)), .Names = c("algo", "rst", 
    "prec", "rorac", "prPo", "pos"), row.names = c(1L, 6L, 4L, 7L, 
    11L, 2L, 5L, 3L, 10L, 9L, 8L), class = "data.frame"), rst5 = structure(list(
        algo = c("Mean", "gbm2", "gbm1", "GAM3", "GAM2", "ran2", 
        "nai1", "GAM1", "svm2", "ran1", "svm1"), rst = c(52.4, 46.4, 
        31.2, 28.8, 28.2, 26.6, 23.6, 20.6, 14.4, 14, 6.2), prec = c(0.441, 
        0.44, 0.416, 0.403, 0.481, 0.422, 0.519, 0.398, 0.386, 0.39, 
        0.37), rorac = c(23.604, 23.2, 16.421, 12.743, 34.815, 18.095, 
        45.385, 11.381, 8.182, 9.091, 3.584), prPo = c(92.9, 83.7, 
        79.5, 94.6, 47.1, 61.5, 30.2, 75.7, 73.6, 64.4, 72.4), pos = c(239L, 
        239L, 239L, 239L, 172L, 239L, 172L, 239L, 239L, 239L, 239L
        )), .Names = c("algo", "rst", "prec", "rorac", "prPo", "pos"
    ), row.names = c(1L, 7L, 6L, 5L, 4L, 11L, 2L, 3L, 9L, 10L, 8L
    ), class = "data.frame")), .Names = c("rst1", "rst5")), T0 = structure(list(
        rst1 = structure(list(algo = c("Mean", "ran1", "GAM1", "GAM2", 
        "gbm1", "svm1", "nai1", "gbm2", "svm2", "ran2"), rst = c(22.6, 
        19.4, 13.6, 10.2, 9.6, 8, 5.6, 3.4, -0.4, -0.6), prec = c(0.478, 
        0.452, 0.5, 0.421, 0.423, 0.833, 0.429, 0.373, 0.355, 0.356
        ), rorac = c(33.731, 26.575, 40, 17.895, 18.462, 133.333, 
        20, 4.533, -0.526, -0.368), prPo = c(34.4, 52.1, 24.3, 40.7, 
        37.1, 3.1, 14.4, 53.6, 54.3, 116.4), pos = c(195L, 140L, 
        140L, 140L, 140L, 195L, 195L, 140L, 140L, 140L)), .Names = c("algo", 
        "rst", "prec", "rorac", "prPo", "pos"), row.names = c(1L, 
        9L, 3L, 4L, 5L, 7L, 2L, 6L, 8L, 10L), class = "data.frame"), 
        rst5 = structure(list(algo = c("gbm1", "ran1", "Mean", "GAM1", 
        "GAM2", "svm1", "nai1", "svm2", "gbm2", "ran2"), rst = c(17.6, 
        16.4, 15, 12.8, 9, 6.2, 5.8, -2.6, -3, -9.2), prec = c(0.466, 
        0.434, 0.435, 0.5, 0.41, 0.8, 0.44, 0.346, 0.345, 0.337), 
            rorac = c(30.345, 21.579, 21.739, 40, 14.754, 124, 23.2, 
            -3.21, -3.448, -5.542), prPo = c(41.4, 54.3, 35.4, 22.9, 
            43.6, 2.6, 12.8, 57.9, 62.1, 118.6), pos = c(140L, 140L, 
            195L, 140L, 140L, 195L, 195L, 140L, 140L, 140L)), .Names = c("algo", 
        "rst", "prec", "rorac", "prPo", "pos"), row.names = c(5L, 
        9L, 1L, 3L, 4L, 7L, 2L, 8L, 6L, 10L), class = "data.frame")), .Names = c("rst1", 
    "rst5"))), .Names = c("F0", "T0"))
于 2018-05-01T21:27:59.507 回答
1

假设我们要计算每个元素的长度。

mylist <- list(a=1:4,b=2:9,c=10:20)
mylist

$a
[1] 1 2 3 4

$b
[1] 2 3 4 5 6 7 8 9

$c
 [1] 10 11 12 13 14 15 16 17 18 19 20

如果目的只是标记结果元素,那么lapply(mylist,length)或以下工作。

sapply(mylist,length,USE.NAMES=T)

 a  b  c 
 4  8 11 

如果目的是在函数内部使用标签,那么mapply()循环两个对象很有用;列表元素和列表名称。

fun <- function(x,y) paste0(length(x),"_",y)
mapply(fun,mylist,names(mylist))

     a      b      c 
 "4_a"  "8_b" "11_c" 
于 2019-07-24T18:17:13.767 回答
1

@ferdinand-kraft 给了我们一个很棒的技巧,然后告诉我们不应该使用它,因为它没有文档记录并且因为性能开销。

我不能对第一点争论太多,但我想指出,开销很少会成为一个问题。

让我们定义活动函数,这样我们就不必调用复杂的表达式 parent.frame()$i[],而只需.i(),我们还将创建.n()访问名称,它应该适用于基本purrr函数(可能还有大多数其他函数)。

.i <- function() parent.frame(2)$i[]
# looks for X OR .x to handle base and purrr functionals
.n <- function() {
  env <- parent.frame(2)
  names(c(env$X,env$.x))[env$i[]]
}

sapply(cars, function(x) paste(.n(), .i()))
#>     speed      dist 
#> "speed 1"  "dist 2"

现在让我们对一个简单的函数进行基准测试,该函数使用不同的方法将向量的项目粘贴到它们的索引中(当然,这个操作可以使用向量化,paste(vec, seq_along(vec))但这不是重点)。

我们定义了一个基准函数和一个绘图函数,并将结果绘制在下面:

library(purrr)
library(ggplot2)
benchmark_fun <- function(n){
  vec <- sample(letters,n, replace = TRUE)
  mb <- microbenchmark::microbenchmark(unit="ms",
                                      lapply(vec, function(x)  paste(x, .i())),
                                      map(vec, function(x) paste(x, .i())),
                                      lapply(seq_along(vec), function(x)  paste(vec[[x]], x)),
                                      mapply(function(x,y) paste(x, y), vec, seq_along(vec), SIMPLIFY = FALSE),
                                      imap(vec, function(x,y)  paste(x, y)))
  cbind(summary(mb)[c("expr","mean")], n = n)
}

benchmark_plot <- function(data, title){
  ggplot(data, aes(n, mean, col = expr)) + 
    geom_line() +
    ylab("mean time in ms") +
    ggtitle(title) +
    theme(legend.position = "bottom",legend.direction = "vertical")
}

plot_data <- map_dfr(2^(0:15), benchmark_fun)
benchmark_plot(plot_data[plot_data$n <= 100,], "simplest call for low n")

benchmark_plot(plot_data,"simplest call for higher n")

reprex 包(v0.3.0)于 2019 年 11 月 15 日创建

第一张图表开始的下跌是侥幸,请忽略它。

我们看到选择的答案确实更快,并且对于相当数量的迭代,我们的.i()解决方案确实更慢,与选择的答案相比,开销大约是 using 开销的 3 倍purrr::imap(),对于 30k 迭代,大约为 25 ms,所以我每 1000 次迭代损失大约 1 毫秒,每百万次损失 1 秒。在我看来,这是为了方便起见的一小笔费用。

于 2019-11-15T10:43:20.150 回答
-1

只需编写自己的自定义lapply函数

lapply2 <- function(X, FUN){
  if( length(formals(FUN)) == 1 ){
    # No index passed - use normal lapply
    R = lapply(X, FUN)
  }else{
    # Index passed
    R = lapply(seq_along(X), FUN=function(i){
      FUN(X[[i]], i)
    })
  }

  # Set names
  names(R) = names(X)
  return(R)
}

然后像这样使用:

lapply2(letters, function(x, i) paste(x, i))
于 2016-08-17T15:56:32.007 回答