I have many .rda
file, which themselves are correctly named, however the variables they each contain (only one per file) are incorrectly labelled. I am attempting to load them into the workspace one by one, rename them to the correct variable name and then save them into a new folder, using the same file name that each file already has.
My attempt is below and the problem is that in the step using assign
, it seems to only be assign the actual name of the variable I'd like to be reassigning. So when I then save this and load it again, I have a variable holding a string, not the actual results.
input_folder <- "/path/to/input_folder/"
output_folder <- "/path/to/output_folder/"
## What I know
A <- "data_chunk" #input name
B <- "results_Lag.1" #variable/data name in workspace
C <- "results.L1.trad_small.rda" #file saved name
load(paste0(input_folder, C)) #load the data into the workspace
to_save <- substr(C, 1, nchar(C)-4) #desired new name in workspace. the -4 loses ".rda"
## Four variations on how to re-assign the data
assign(to_save, B)
assign(to_save, get(B))
assign(to_save, as.name(B))
assign(to_save, eval(parse(B)))
## Save the data with new vairable name to new folder
save(list = to_save, file = paste0(output_folder, C))
As you can see from the three variations, I have seen several ways ([1][2][3]) to call a variable from the workspace using a string.
The first three simply save my my string , while the last variations using B
as the variableeval(parse())
returns an error:
> assign(to_save, eval(parse(B)))
Error in file(filename, "r") : cannot open the connection
Calls: assign -> eval -> parse -> file
In addition: Warning message:
In file(filename, "r") :
cannot open file 'glm_results_Lag.1': No such file or directory
Calls: assign -> eval -> parse -> file
If I call get(B)
in the console, it does return the contents of the variable as expected.
EDIT
As @joran says in the comments, the second variant does produce the expected result, saving the data to the specified string:
assign(to_save, get(B))
The size of the new object on disk, however, is different to that of the loaded file (As i mention in the comments).
I have no explanation for this...