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)
Is there a way I can somehow make it print “Adding Values: 1” “Adding Values: 2” etc.. one element of each in the list?
Thanks!
The function
mapplyworks likelapplybut 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:
Let’s try it:
Result:
Advanced user fun
Just for fun, a careful reading of the
?lapplymanual page reveals that the following also works: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:
Now the adaptor
and now the lapply call, with the adaptor: