1

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.

4
  • 2
    This is likely an XY problem. Whenever you find yourself wondering how to loop over a collection of variables which differ in name only by a tacked-on integer, there is a vector or list waiting to be born. Why not have the conditions in 1 data structure rather than 9 variables? That way you wouldn't need hacks involving things like eval. Commented Oct 28, 2022 at 1:13
  • I am currently doing a simulation study that does 100 replications within each condition. So i am looping between each condition (stored as a vector so that i can do x from 1:9)), and then doing 1 for loop that does the replications. I need to store the replications/values before looping back to the conditions though because I only want to make 1 for loop that does the replications, but some of the variable names will need to change from results$con1... to results$con2 after doing the first 100 reps and so on. Commented Oct 28, 2022 at 1:21
  • @JohnColeman see edits please. Commented Oct 28, 2022 at 1:28
  • I've never used code like that so I don't know how to debug it. Commented Oct 28, 2022 at 1:30

2 Answers 2

3

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.)

Sign up to request clarification or add additional context in comments.

Comments

1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.