-1

I'm learning about looping análisis in R, in order to improve efficiency of my code. However, i couldn't find how to create object which name (or part of its name) change in those loops.

Could you help me with this? Here's some code that works and another code that doesnt, but is expressive about my search.

Thank you all!!!!


####----THESE CODES WORK-----####

anio=17:21
for (i in anio) {
 print(i-16)
}

#THIS WORKS
for (i in anio) {
  print(paste0("a",i-16))
}

for (i in anio) {
print(sprintf("obj_%s",i))
}

####----THIS CODE DON'T WORK-----#### 

#    Attempt to create object with loops

anio=17:21
for (i in anio) {
sprintf("obj_%s",i)=i-17
}


#    Here are some more elaborate examples where I would like to "loop" between....   #........different df's and variables, creating objects whose names also change.

# objects whose name I would like to change when switching between years and variables:  

# dise2021, esi2021, a1,

dise2021 <- esi2021 %>%    ##creating survery design for srvyr
  as_survey_design(ids = id_directorio,  
                   strata = estrato, 
                   weights = fact_cal_esi)
options(survey.lonely.psu="remove") 


a1<-dise2021 %>% #dise2019:  ##survey design for srvyr
filter(ocup_ref==1) %>% 
summarise(ing_medio = survey_mean(ing_t_p, vartype="cv",na.rm=T)) 
  • Its usually better in R not to have variable names with indexes/data in the name themselves. In R it's better to use named lists. It makes it easier to iterate over values and perform transformations. – MrFlick Sep 01 '22 at 19:19

1 Answers1

-1

I think creating a new object for every iteration of a for loop will lead to massive memory usage while being very inefficient for further use. You should consider making a dataframe where one column has the name of the im gonna guess year, and the other column has the year. Or maybe you are trying to make a list of years? Then you should use a list/vector in R to store your data, instead of making a new object for every iteration