-1

Based on calculations I have created a list, which contains 10 lists named by year (e.g. y2000 for 2000) and each year-list contains, in its turn, two result matrices (A and B).

For analysis purpose I would like to create a variable year and matrix, assign values to them. For instance: year = 2000 and matrix = A Based on this variables I would like to return a desired matrix.

I tried to use get() with paste0() and different ways of list-notation, however none of the tries returned the result.

If I run Data$y2000$A - the matrix is being returned, but

get(paste0("Data[[y",year,"]][[",matrix,"]]))

returns an error

object 'y2000' not found

also I have tried to use brackets and backticks, but it still returns the same error.

get(paste0("Data[[`y",year,"`]][[`",matrix,"`]]))

How one can return an object via a variable?

Vinícius Félix
  • 8,448
  • 6
  • 16
  • 32
Timur
  • 15
  • 2
  • 1
    It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. It's best to avoid `get()` and `assign()` especially considering you can't use them with functions like `[[]]` and `$` in the variable "names". – MrFlick Sep 20 '21 at 19:08

1 Answers1

2

We don't need get here. Instead extract the elements dynamically by creating the element names of 'Data' with paste

Data[[paste0('y', year)]][[matrix]]
akrun
  • 874,273
  • 37
  • 540
  • 662