-5

I need to include different numbers (result of a loop function) in the name of a data frame which I am trying to read at the same time. However, I do not know how.

Example, of what I am looking for are names of these dataframes:

data.1
data.2
data.3

An example of what I tried to do (which did not work, but illustrates better my question) is:

for (a in 1:3) data.(a) <- read.csv2(file.csv, header = TRUE)

Is it possible to include different numbers in the names of dataframes? If yes, how, please?

Sorry for beginner's question, but I have not found it anywhere.

Jakub Drapal
  • 233
  • 2
  • 3
  • 8
  • 7
    This is not typically how we do things in R. If you are reading multiple files, you would do that via `lapply` which will give you a list of data frames. Then you can set the names of the list to be whatever you want. – joran Apr 27 '16 at 15:17
  • Thanks, but I am not trying to read multiple files, but one file several times with which I am then working differently. – Jakub Drapal Apr 27 '16 at 15:22
  • 1
    See the follow answer on [working with lists of data.frames](http://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207). It is the way to go. – lmo Apr 27 '16 at 15:23
  • You would still want to put all copies of it in a single, named list. Try initializing an empty list before the `for` loop via `l <- setNames(vector("list",3),paste("data",1:3,sep = ".")`. And then assign each copy to `l[[a]]` in the for loop. – joran Apr 27 '16 at 15:25
  • 4
    So why would you need to assign them to different variables? At the very least, you should be using a list (even if they are all the same data.frame). It will make things much easier to work with downstream. You can use `data<-replicate(3, read.table("file"))` to read the same file in three times. Then you can extract them with `data[[1]]`, `data[[2]]`, etc – MrFlick Apr 27 '16 at 15:25

1 Answers1

-3

Although I agree with joran in this case, sometimes it can be useful to use the assign() function, for instance as follows:

for (i in 1:3) {
  assign(paste0("data.", i), i)
}

This results in the following:

> ls()
[1] "data.1" "data.2" "data.3" "i"     
> data.1
[1] 1
> data.2
[1] 2
> data.3
[1] 3
tomtom
  • 259
  • 1
  • 2
  • 6