1

I have the repetitive task of extracting parts of a list and saving them to a new variable name.

I can use aaa_report <- original[["aaa"]] and I have a new variable named aaa_report which is a the aaa section from the list variable original

Now I would like to automate this repetitive task:

aaa_report <- original[["aaa"]]

bbb_report <- original[["bbb"]]

ccc_report <- original[["ccc"]]

...

I have a separate "character" list variable named dept with all the names dept <- c("aaa", "bbb", "ccc", "...")

I try to use sapply and get this error.

sapply(dept, function(x) x"_report" <- original[[x]])

Error: unexpected string constant in "sapply(dept, function(x) x"_report""

I have tried all the apply family and a for loop with no luck.

for(x in dept){
  x"_report" <- original[[x]]
}

I am a beginner to R and programming in general, so any advice will be much help.

adm
  • 304
  • 4
  • 17
  • Why not just keep them in the list and reference them when needed? This seems like a more reasonable way to go. See gregor's answer on [this post](http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames) for a number of useful methods to run through named list elements. – lmo Dec 22 '16 at 19:37
  • I will use the pieces of the list later combined in a different way – adm Dec 22 '16 at 19:40
  • If you really want to do this (keeping stuff in lists is nearly always best) use `get(paste0(x, "_report"))` – Richard Telford Dec 22 '16 at 19:47
  • As stated by the 2 comments above, make a list a keep a list, it's way better. And you may also want to look at the function `split` which will make it for you. After, do all your analysis with `lapply` or `sapply`directly on your list – Bastien Dec 22 '16 at 19:47

1 Answers1

0

You were close, use the assign function:

for(x in dept) assign(paste0(x, "_report"), original[[x]])

It would not work with the apply functions, since the assignment will be in the local environment of the apply function.

As stated in the comments, keeping everything in a list is always better.

dimitris_ps
  • 5,391
  • 1
  • 21
  • 46