首页 > 解决方案 > How to assign and dynamically change the name of a dataframe in R in a loop

问题描述

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

标签: r

解决方案


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)
  
}

推荐阅读