repetitive task in R with a character string using sapply or a for loop

252 Views Asked by At

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.

1

There are 1 best solutions below

0
On BEST ANSWER

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.