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))
Let's try it:
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))
Result:
Adding values ( 1 ): 5 ... 4 = 9
Adding values ( 2 ): 3 ... 2 = 5
Adding values ( 3 ): 1 ... 3 = 4
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])
}
Now the adaptor
lapply_index_adaptor=function(f)function(x,...)f(x,substitute(x)[[3]],...)
and now the lapply call, with the adaptor:
lapply(mylist, lapply_index_adaptor(myfunction))