0

I'm trying to create a loop that goes from 1 to 14. Each integer in this loop would be added to the end of the name of a newly created dataframe. Then, it should search a column in an existing dataframe based on the concatenation of a number and text. I've been searching for hours but cannot find a solution.

What I mean is:

while (i <= 14) {
    "newDF" + i <- oldDf %>%
         filter(str_detect(ColumnName, "TEXT" + i)

}

The new dataframes should look like this:

newDF1,newDF2... newDF14

They should be created based on a concatenated string (text + i):

text1,text2..text14

My first challenge is to create a new dataframe based on the concatenation of text and i. I've tried using the str_c command and the str_glue command but get the following error message.

Error in str_c("newDF", i)) <- oldDF: 
  target of assignment expands to non-language object


Error in str_glue("newDF{i}") <- oldDF: 
  target of assignment expands to non-language object
  • When you need to loop, use a `while` loop when you don't know how many times the loop will run - you need a test to figure out when to stop. Use a `for` loop when you know in advance how many times to loop. In this case, you know your loop goes from 1 to 14, so use `for (i in 1:14)`. – Gregor Thomas Jun 04 '18 at 14:49
  • 2
    But also don't do this. Sequentially named variables are very difficult to work with (as you've found out). Instead, put them all in a list. [Read my answer here about using lists of data frames](https://stackoverflow.com/questions/17499013/how-do-i-make-a-list-of-data-frames/24376207#24376207). It is much easier. – Gregor Thomas Jun 04 '18 at 14:50
  • @Gregor Thanks - great answer – Lukas Barth Jun 05 '18 at 07:23

1 Answers1

0

The major problem with your code above is that you can't have any operations to the left of your assignment operator.

for (i in 1:14){
    assign(str_glue("newDF{i}"), oldDF %>%
         filter(str_detect(ColumnName, str_glue("TEXT{i}"))))
}

So technically, this would work even though I feel like there's a better way to do this either with nested lists or using spread and gather. I would say more, but I don't have enough context to solve the problem.