Home > Enterprise >  How to use a for loop with multiple results
How to use a for loop with multiple results

Time:09-28

I have to automate this sequence of functions:

for (i in c(15,17,20,24,25,26,27,28,29,45,50,52,55,60,62)) {

WBES_sf_angola_i <- subset(WBES_sf_angola, isic == i)
WBES_angola_i <- as_Spatial(WBES_sf_angola_i)             

FDI_angola_i <- FDI_angola[FDI_angola$isic==i,]           

dist_ao_i <- distm(WBES_angola_i,FDI_angola_i, fun = distGeo)/1000    

rm(WBES_sf_angola_i,WBES_angola_i,FDI_angola_i)
}

As a result, I want a "dist_ao" for each i. The indexed values are to be found in the isic columns of the WBES_sf_angola and the FDI_angola datasets.

How can I embed the index in the various items' names?

EDIT:

I tried with following modification:

for (i in c(15,17,20,24,25,26,27,28,29,45,50,52,55,60,62)) {

WBES_sf_angola_i <- subset(WBES_sf_angola, isic == i)
WBES_angola_i <- as_Spatial(WBES_sf_angola_i)             

FDI_angola_i <- FDI_angola[FDI_angola$isic==i,]           

result_list <- list()
  
result_list[[paste0("dist_ao_", i)]] <-  distm(WBES_angola_i,FDI_angola_i, fun = distGeo)/1000  

rm(WBES_sf_angola_i,WBES_angola_i,FDI_angola_i)
}

and the output is just a list of 1 that contains dist_ao_62. Where do I avoid overwriting?

CodePudding user response:

Untested (due to missing MRE) but should work:

result_list <- list()

for (i in c(15,17,20,24,25,26,27,28,29,45,50,52,55,60,62)) {

  result_list[[paste0("dist_ao_", i)]] <-  distm(as_Spatial(subset(WBES_sf_angola, isic == i))  , FDI_angola[FDI_angola$isic==i,], fun = distGeo)/1000  

}

CodePudding user response:

You could approach it this way. All resulting dataframes will be included in the list, which you can convert to a dataframe from the last line of the the code here. NOTE: since not reproducible, I have mostly taken the code from your question inside the loop.

WBES_sf_angola_result <- list() # renamed this, as it seems you are using a dataset with the name WBES_sf_angola
WBES_angola <- list()
FDI_angola <- list()
dist_ao <- list()


for (i in c(15,17,20,24,25,26,27,28,29,45,50,52,55,60,62)) {
  
  WBES_sf_angola[[paste0("i_", i)]] <- subset(WBES_sf_angola, isic == i)
  WBES_angola[[paste0("i_", i)] <- as_Spatial(WBES_sf_angola_i)             
  
  FDI_angola[[paste0("i_", i)] <- FDI_angola[FDI_angola$isic==i,]           
  
  dist_ao[[paste0("i_", i)] <- distm(WBES_angola_i,FDI_angola_i, fun = distGeo)/1000    
  
  rm(WBES_sf_angola_i,WBES_angola_i,FDI_angola_i)
}

WBES_sf_angola_result <- do.call(rbind, WBES_sf_angola_result) # to get a dataframe

Your subset data can also be accessed through list index. eg.

WBES_sf_angola_result[[i_15]] # for the first item. 
  • Related