0

I have these lists: models_results_ZL, models_results_B2 and models_results_B4 that contain numbers.

For example:

> models_results_ZL
[1] 245.1907896  29.9200000   0.9000181  34.0000000
> models_results_B2
[1] 264.9851283  53.7100000   0.9163977  32.0000000
> models_results_B4
[1] 289.7529856  52.5600000   0.9229745  31.0000000

I have the list both_constr_satisfied that contains "B2","B4". This list is not static. It may contains different combinations of "ZL", "B2" and "B4". For example:

> both_constr_satisfied
[1] "B2" "B4"

Regarding the values of both_constr_satisfied I want to get the first value of the corresponding models_results lists. e.g. For this example I want to get models_results_B2[1] and models_results_B4[1] and store them to a new list. e.g. new_list = [264.9851283, 289.7529856]

How can I concatenate strings and use them as a list name?

I'm trying the following code, but var_name is just a string not a list.

VQ_options=c()
for (option in length(both_constr_satisfied)){
    assign(var_name, paste0("models_results_",both_constr_satisfied[option+1]))
    VQ_options = var_name[1]
  }
2
  • Can you please add reproducible example of both model_results and both_constr_satisfied lists Commented May 8, 2017 at 9:07
  • @Sotos There is no list named model_results. There are 3 different lists that have the same initial name. model_results_ZL, model_results_B2 and model_results_B4. I want to concatenate model_results with the values of both_constr_satisfied and use these as lists. I added examples of these. I will add also for both_constr_satisfied. Commented May 8, 2017 at 9:10

1 Answer 1

1

You can try:

# Some data 
a <- list(models_results_ZL=1:10, models_results_B2=10:1, models_results_B4=11:20)
a
$models_results_ZL
[1]  1  2  3  4  5  6  7  8  9 10

$models_results_B2
[1] 10  9  8  7  6  5  4  3  2  1

$models_results_B4
[1] 11 12 13 14 15 16 17 18 19 20

both_constr_satisfied <- list(c("B2", "B4"))

# change names according the both_constr_satisfied list
a <- setNames(a, unlist(lapply(strsplit(names(a), "_"), "[", 3)))
names(a)
[1] "ZL" "B2" "B4"

# extract the first value, respectively
lapply(a[unlist(both_constr_satisfied)], "[", 1)
$B2
[1] 10

$B4
[1] 11
Sign up to request clarification or add additional context in comments.

1 Comment

Great! Thank you!!

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.