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.
You were close, use the
assignfunction:It would not work with the
applyfunctions, since the assignment will be in the local environment of theapplyfunction.As stated in the comments, keeping everything in a list is always better.