带索引的R lapply语句 [英] R lapply statement with index
问题描述
有没有一种方法可以使lapply语句也显示索引?更具体地说,请考虑以下示例:
Is there a way I can make an lapply statement also show the index? More specifically, consider the following example:
mylist <- list(c(5,4),c(3,2), c(1,3))
myfunction<- function(values){
print("Adding values: ")
return(values[1] + values[2])
}
lapply(mylist, myfunction)
有没有办法让我以某种方式打印"Adding Values:1"(添加值:1)"Adding Values:2"(添加值:2)等.列表中每个元素的一个元素?
Is there a way I can somehow make it print "Adding Values: 1" "Adding Values: 2" etc.. one element of each in the list?
谢谢!
推荐答案
函数mapply
的作用类似于lapply
,但允许您提供多个向量或列表.
The function mapply
works like lapply
but allows you to supply multiple vectors or lists.
在您的情况下,您可以创建第二个向量,该向量与列表的长度相同,只需向上计数即可:
In your case you can create a second vector, the same length of the list, just counting up:
mapply(myfunction, mylist, seq_along(mylist))
让我们尝试一下:
myfunction<- function(values, index){
cat("Adding values (", index, "): ", values[1], "...", values[2], " = ", sum(values), "\n" )
invisible(values[1] + values[2])
}
mylist <- list(c(5, 4), c(3, 2), c(1, 3))
mapply(myfunction, mylist, seq_along(mylist))
结果:
Adding values ( 1 ): 5 ... 4 = 9
Adding values ( 2 ): 3 ... 2 = 5
Adding values ( 3 ): 1 ... 3 = 4
高级用户乐趣
仅出于娱乐目的,仔细阅读?lapply
手册页后,发现以下内容同样适用:
Advanced user fun
Just for fun, a careful reading of the ?lapply
manual page reveals that the following also works:
myfunction<- function(values){
print(sprintf("Adding values: %i",substitute(values)[[3]]))
return(values[1] + values[2])
}
lapply(mylist, myfunction)
这建议可以创建一个通用函数适配器来为原始函数(或任何其他函数)提供索引,并对其进行修改以期望有第二个索引参数:
Which suggests a general function adaptor could be created to supply index to your original function (or any other), modified to expect a second index argument:
myfunction<- function(values,index){
print(sprintf("Adding values: %i",index))
return(values[1] + values[2])
}
现在是适配器
lapply_index_adaptor=function(f)function(x,...)f(x,substitute(x)[[3]],...)
,现在是使用适配器的lapply调用:
and now the lapply call, with the adaptor:
lapply(mylist, lapply_index_adaptor(myfunction))
这篇关于带索引的R lapply语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!