For example, I have 9 conditions lets say and i want to store the seed number within a loop that goes into the results list that contains con1-con9. In my actual code the seed number will be changing, but just have this here for simplicity.
seed <- 500
for(x in 1:length(results)){
results$con1$seednum <- seed
}
I thought something like this, but does not seem to work.
eval(parse(text= paste0("results$con", x)))$seednum <- 500
How can i have this such that the con1 will change to con2, con3...etc through the for loop and be able to store that seed value in each results$con1 through results$con9? I assume it has something to do with eval and parse while using the x index, but I am not sure how it can be done.
Thank you.
CodePudding user response:
First, please put the elements on a list.
my_list <- mget(ls(pattern='con\\d ')
Then use a loop function to append
the seed.
library(purrr)
my_list %>%
map(append, seed)
CodePudding user response:
Study help("$")
. You want to use [[
here. In general, $
is mainly intended for interactive use.
seed <- 500
for(x in 1:length(results)){
results[[paste0("con", x)]][["seednum"]] <- seed
}
Never use eval(parse())
. That would lead to nightmare scenarios for anyone who has to debug your code. That includes future you. (Also, parsing is slow.)