0

I am trying to make my code shorter using loops. I have an object, of which several "sub-objects" exist, which I appended with a letter, i.e.

my_object_a
my_object_b
my_object_c

Now I was planning on manipulating those objects, say I want to log2 the second column of each of those. I thought it would be handy to just store a, b, and c in a vector and then using paste() and get() like so:

letter <- c("a", "b", "c")
for (i in 1:length(letter){
       get(paste0("my_object_", id[i])) <- MadeUpFunction(get(paste0("my_object_", id[i])))
}

My question is: how would one usually approach such kind of problem in order to avoid automate a repetitive task?

I feel like somebody might suggest a named list here, but then I have to pop them back out of the list, right?

Btw, the function in the loop as well as the exact object dont really matter, lets just say its each a complex object and I would apply a custom function to them, for example normalization from a package.

Any help will be appreciated.

ic23oluk
  • 125
  • 1
  • 9
  • 3
    (1) If you're doing the same thing to multiple related objects, it's better to deal with them as a [list of frames](https://stackoverflow.com/a/24376207/3358227). I'd start with `objs <- list(a=my_object_a,b=my_object_b,...)`, then `objs <- lapply(objs, MadeUpFunction)`. (2) `get(.)<-` is not a thing. While I discourage this workflow, look for `assign(.)`. – r2evans Aug 15 '21 at 12:50
  • Thank you. Will check out the list of frames post. One thing is that further downstream my workflow I will treat the objects differently, so at that point it is not handy anymore to have them in a list. Would you still go for this approach? – ic23oluk Aug 15 '21 at 12:59
  • 1
    For me, it depends on how much commonality there is in the processing. For instance, if there is a step that only applies to two, then one can do `objs[c("a","d")] <- lapply(objs[c("a","d")], SomeFunc)`; if only one, then `objs[["e"]] <- OtherFunc(objs[["e"]])` works. I understand the nature of your not-always-identical flow, I cannot tell you where your balance will be :-) – r2evans Aug 15 '21 at 13:21

0 Answers0