verify a loop is calling elements with the same name from multiple lists

41 Views Asked by At

I have two large lists (over 700 elements) that have the same element names. The next step in my analyses is to calculate confidence intervals via a bootstrapping function written in C++. To use the function, I need to call elements from both lists, the raw data for a given individual and the model output for that individual. My supervisor is concerned that the loop does not "match" element names between lists. Since one list was created from a function looped over the other list, and neither list has had elements rearranged I am not overly concerned that there will be calls to non-matching elements, but it would be nice to make sure that the names match before running the function if we end up using this bootstrap function on data not generated via the same means as the current lists.

example lists:

lst_A <- list(
  m1 = matrix(1:12, nrow = 4), 
  m2 = matrix(1:9, nrow = 3), 
  m3 = matrix(1:6, nrow = 2)
)

lst_b <- list(m1 = c(t1 = 2, t2 = 2, r0 = 2, r1 = 2, k0 = 2, k1 = 2), 
m2 = c(t1 = 1, t2 = 1, r0 = 1, r1 = 1, k0 = 1, k1 = 1), 
m3 = c(t1 = 10, t2 = 10, r0 = 10, r1 = 10, k0 = 10, k1 = 10))

lst_A is a list of matrices of raw data, each matrix has the same number of columns but varying in number of rows. Matrices were required by the function that created lst_b, a list of lists.

I have a loop similar to the following that writes the results to another list:

out <- list()
ci_outs_names <- names(lst_A) 
for (i in seq_along(lst_A)) { 
  CIs = (lst_A[[i]] * lst_b[[i]])
  out[[ci_outs_names[i]]] <- CIs
}

I have not found an option to match elements of a list in a loop. Is this possible using loops, or is there another method that would allow element name matching when using multiple lists to inform a function? Please note that I am unable to modify the C++ code/functions.

If helpful, the "real" loop code is:

ci_out <- list()
ci_outs_names <- names(lst_A) 
for (i in seq_along(lst_A)) { 
    sourceCpp("cpp_functions.cpp") 
    CIs = bootstrap_CI(data_in = lst_A[[i]],
                       optim_pars = lst_b[[i]], 
                       n_iter = 100, 
                       times_matrix = times_matrix, intervals = c(14, 7, 3, 1), NLL_include = 5, cpp = TRUE) # These are all just additional arguments to another function which is called inside of this function
    ci_out[[ci_outs_names[i]]] <- CIs
   }

Note (probably not relevant to this question, but I will mention just in case): This code consistently crashes RStudio (white screen) even with n_iter = 10 and lists of 2 elements. A scaled-down version (n_iter = 50) of this loop works on the full dataset in the console.

1

There are 1 best solutions below

2
ThomasIsCoding On

Probably you are after something like this

Map(`*`, lst_A, lst_b[names(lst_A)])