How can I select the second column of a dynamically named variable?
I create variables of the form “population.USA”, “population.Mexico”, “population.Canada”. Each variable has a column for the year, and another column for the population value. I would like to select the second column from each of these variables during a loop.
I use this syntax:
sprintf("population.%s", country)[, 2]
R returns the error: Error in sprintf("population.%s", country)[, 2] : incorrect number of dimensions
See
?get. Here is an example:It is critically important to look at the object returned by a function if you get an error. It is immediately clear why your example fails if you just look at what it returns:
At that point it would be immediately clear, if you didn’t already know or have thought to read
?sprintf, thatsprintf()returns a string not the object of that name. Armed with that knowledge you would have narrowed down the problem to how to recall an object from the computed name?