2

In javascript, I am used to using the map function at this point. The callback for the map function takes two (really, three) arguments: the value and the index, like so:

someArray.map((value, index) => { // do stuff })

I'm new to R, but have noticed that the apply method is similar in that you provide some sort of data structure and then a function to run on each data element.

However, I haven't seen in the docs anywhere where I can let that function be aware of the index. Something like:

lapply(some_list, function(val, idx) print(idx))

which I would hope to output:

1
2
.
.
.
n - length of list

Am I missing something, or is this not possible in R?

MrFlick
  • 178,638
  • 15
  • 253
  • 268
fraxture
  • 4,653
  • 3
  • 39
  • 76
  • Please show a small reproducible example and expected output – akrun Aug 06 '16 at 19:48
  • You could use a for loop, which might not be optimal from a performance point of view, but would let you keep track of the loop index. – Tim Biegeleisen Aug 06 '16 at 19:54
  • Yes @TimBiegeleisen, I thought about that as well, but was curious to know whether this is actually not possible in R. Would seem odd given that this "mapping" pattern is mostly there. – fraxture Aug 06 '16 at 19:55

0 Answers0