I have 6 data frames in the global environment which I created thus:
for (i in 1:6){
assign(paste0("bestpredX",i),
allfits[allfits$iteration == apply(results.dat, 2, which.min)[i],
c("X_var", "Y_var", paste0("X",i), "iteration")])
}
Which returns a data frame of this format:
X_var Y_var X1 iteration
2829 69 151 135.8836 29
2830 64 131 140.3848 29
2831 67 129 137.6841 29
<...>
Then, I want to perform the same changes on each of these dfs (truncated for simplicity):
# Add a column 'Polynomial' and fill it all with factor Xi
bestpredX1$Polynomial <- as.factor("X1")
bestpredX2$Polynomial <- as.factor("X2")
<...>
bestpredX6$Polynomial <- as.factor("X6")
# Rename the 3rd column (Xi) to y.fit
names(bestpredX1)[names(bestpredX1) == "X1"] <- "y.fit"
names(bestpredX2)[names(bestpredX2) == "X2"] <- "y.fit"
<...>
names(bestpredX6)[names(bestpredX6) == "X6"] <- "y.fit"
I am not able to perform these in a for-loop using get(paste0("bestpredX",i))
, from what I understand it's because the variables already exist in the global environment. How can I go about for-looping operations on existing variables dynamically?
Note: In the present case I presume there might be a way to do all these even in the first for-loop. But I would like to learn how to perform it on existing variables; it's a task I encounter often.
Thanks!