2

Sorry I'm a newbie in R.
I have multiple data frames, product.43, product.98, product.103, that contain the sales of each product over the time and have another variable, index, that contains the codes for each product:

 products
    43
    98
    103

If I do one by one it should be something like this:

plot(product.43[,3],product.43[,2],type="o")
plot(product.98[,3],product.98[,2],type="o")
plot(product.103[,3],product.103[,2],type="o")

what I'm trying to do is this:

plot(product.i[,3],artigo_agreg.i[,2],type="o")

So I want to substitute the i for the product code that is in index with a for loop.

Barranka
  • 20,547
  • 13
  • 65
  • 83
Zé Pinho
  • 83
  • 1
  • 1
  • 6
  • possible duplicate of [Referring to objects using variable strings in R](http://stackoverflow.com/questions/10588008/referring-to-objects-using-variable-strings-in-r) – Barranka Oct 02 '14 at 15:48
  • You're best off having the data.frames in a list rather than as separate objects. Then looping through them is trivial, and you can also do nicer things with `lapply`. – Gregor Thomas Oct 02 '14 at 15:56

1 Answers1

2

Use get(). Here is an example:

abc.1 <- 123
abc.2 <- 456

for(i in 1:2){
  var <- paste('abc', i, sep='.')
  x <- get(var)
  print(x)
}
## [1] 123
## [1] 456

As you can see, you can create a variable (var) that holds the name of the variable you want to use. Then , you can get() the value of the variable using its name.

In your specific case, this would be something like this:

for(i in index) {
  var <- paste('product', i, sep='.')
  product.i <- get(var)
  # Do whatever you need to do with product.i
}
Barranka
  • 20,547
  • 13
  • 65
  • 83