0

Basically I want to be able to do this.

a <- 1
data_frame_1 <- "some data"
a <- a+1
data_frame_2 <- "some data"

Where the 1 and 2 at the end of the data frame names are coming from the values of a. Is there a way to do this?

  • 4
    It is better to use a list of data frames. – jogo May 30 '19 at 19:03
  • 3
    Do not follow advice pointing you towards the use of `assign`. The same effect can be achieved in R, but you have to think a little differently as noted in the first comment. Create a list of data frames, which you can append to if necessary. You can set the names of the list elements using `setNames`. – joran May 30 '19 at 19:05
  • [Here's a list](https://stackoverflow.com/q/17559390/5325862) of reasons to not use `assign` – camille May 30 '19 at 19:35

2 Answers2

0

As a simple example:

my_list <- list(data_frame_1,data_frame_2)
my_list <- setNames(my_list,paste0("data_frame_",1:2))
joran
  • 169,992
  • 32
  • 429
  • 468
-1

You can do this using assign. Check out these links for reference.

Error in : target of assignment expands to non-language object

Create a variable name with "paste" in R?

assign(paste0("data_frame_",a), "some_data")
rfortin
  • 184
  • 8
  • It's true that you *can* do this, but it's a pretty poor practice and there are better alternatives, such as creating a list – camille May 30 '19 at 19:35
  • @camille Are you saying using ``assign()`` is always a poor practice? Because I am using it in a group of multiple functions that send an email and the function was really helpfull. Creating a list was not an option for my function tho. I just want to know why ``assign()`` got a bad reputation, thank you. – Gainz May 30 '19 at 19:52
  • I don't know that I'd say it's always a poor practice, but I can't think of any good reasons to use it. My comment up top links to an SO post that goes through reasons against using it – camille May 30 '19 at 19:55
  • 1
    @camille The following provides "a" good use, but certainly not useful in this case. https://stackoverflow.com/a/9966441/9555388 – Hector Haffenden May 30 '19 at 20:07