0

Hi am trying to create dataframes in a loop with different names, what is assigned to them is a filter from another dataframe inside the loop

here is the code I have so far

for (i in 1:nrow(data_s_y_revenue)){
  
  name_y <- data_s_y_revenue$year[i]
  
  data_y_y <-filter(data_y, year==name_y)
  
  
}

the name_y is a variable that as it loops it gets a year value, 2018, 2019,2020, etc, as the code is right now the dataframe data_y_y gets rewritten every time, what I would like to end with is a way that the name of the variable has the VALUE of name_y variable on its name, and I end with as many dataframes as years there is, for example if I have only year 2019 and 2020, I would end with 2 dataframes with names 2020_data_y_y and 2019_data_y_y with the values of the filter for those years.

Thanks for the help.

some data example data_s_y_revenue data:

year 
2018
2019

data_y data:

year   value value2
2018   1     4
2018   2     4
2019   3     2
2019   3     2

the expected result would be 2 dataframes called 2019_data_y_y and 2020_data_y_y with the filtered values

3
  • Please provide some example data and the expected output (show us the structure/data you expect as output). I'm sure there's a better way than using a loop Commented Sep 24, 2020 at 19:21
  • you could have a look at assign Commented Sep 24, 2020 at 19:27
  • @Waldi I was able to make it work with your suggestion. Commented Sep 24, 2020 at 19:51

1 Answer 1

2

With the suggestion of Waldi I was able to solve it

for (i in 1:nrow(data_s_y_revenue)){
  
  name_y <- data_s_y_revenue$year[i]
  
  name_y1 <- paste("data_y_y",name_y, sep="_")
  data_y_y <-filter(data_y, year==name_y)
  
  assign(name_y1, data_y_y)
  
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.