0

I am trying to add a row NewRow to each matrix in a list mylist. NewRow should be a vector of integers from 1 until the end of the row. Each matrix in mylist has a different number of columns, so the last number in the NewRow vector isn't constant, it has to be dynamic. These are my attempts:

mylist.with.new.row <- lapply(mylist, rbind, NewRow = 1:ncol())
mylist.with.new.row <- lapply(mylist, rbind, NewRow = 1:ncol(mylist))

Neither work because ncol() can't be empty, but also can't just be ncol(mylist) because it has to be dynamic. I assume this can be done with a loop but I'm hoping someone knows a quicker way. Thanks!

justin
  • 11
  • 2
  • If you need a value from the iteration, you'll need to use a function. `lapply(mylist, function(x) rbind(x, NewRow = 1:ncol(x)))`. At least I think that's what you want. It would be more clear if you provided a [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and the desired output. Another alternative might be: `Map(rbind, mylist, lapply(lengths(mylist), seq.int))` – MrFlick Jan 22 '21 at 17:38
  • That works, thank you! – justin Jan 22 '21 at 17:42

0 Answers0