2

I have 3 data frames called 'first', 'second' and 'third'

I also have a string vector with their names in it

 frames <- c("first","second","third")

I would like to loop through the vector and refer to the data frames

for (i in frames) {

  #set first value be 0 in each data frame
  i[1,1] <- 0
}

This does not work, what am I missing?

jenswirf
  • 7,087
  • 11
  • 45
  • 65
  • 2
    Take a look at `?get` and/or `?assign` but also realize that there is probably a better way to do what you actually want to do. – Dason Oct 15 '12 at 14:19
  • 2
    I think you want `get(i)`. But like Dason said, there is probably a better way. a list of data.frames for example. – Justin Oct 15 '12 at 14:21

2 Answers2

3

This is really not the optimal way to do this but this is one way to make your specific example work.

first <- data.frame(x = 1:5)
second <- data.frame(x = 1:5)
third <- data.frame(x = 1:5)

frames <- c("first","second","third")

for (i in frames) {
 df <- get(i)
 df[1,1] <- 45
 assign(as.character(i), df, envir= .GlobalEnv)
}


> first
   x
1 45
2  2
3  3
4  4
5  5
> second
   x
1 45
2  2
3  3
4  4
5  5
> third
   x
1 45
2  2
3  3
4  4
5  5
Maiasaura
  • 32,226
  • 27
  • 104
  • 108
2

As Justin mentioned, R way would be to use a list. So given that you only have the data frame names as strings, you can copy them in a list.

frames <- lapply(c("first", "second", "third"), get)
(frames <- lapply(frames, function(x) {x[1,1] <- 0; x}))

However, you are working on a copy of first, second and third within frames.

Etienne Racine
  • 1,323
  • 1
  • 11
  • 25