make a loop for multiple bases

I have 4 bases and I need to create a loop to apply the same function to each one. The problem is that since these are not the only objects that I have stored in R's storage, I can't think of how to tell R the name of the bases in an automated way.

I thought of putting them together in a folder and doing this:

Like for example i have in a folder "base1.xslx", "base2.xlsx", "base3.xlsx" and "base4.xlsx".

First I import the bases:

for (i in list.files("Data/Bases/Cruda/")){
  
  path<-i %>%
    str_remove(., "(?<=.)\\..+") 
  
  assign(path, read_excel(paste0("Data/Bases/",
                                 i)))
   
}

And I need to create an object for each base that is a table where in one column are the names of the variables and in the next column the position occupied by those variables. So I do:

for (i in list.files("Data/Bases/")){
  
  path<-i %>%
    str_remove(., "(?<=.)\\..+") 
  
  assign(paste0("vector_",
                path), 
         tibble(posicion= 1:length(names(path)),
                      variable= names(path)))
  
}

Where path represents the database name without the ".xlsx".

The problem in this loop is that since it is a character class path, it does not recognize it as an object, therefore it only generates a single column called position with two observations 1 and 0.

How can I generate this loop and apply (in this case) the tibble to each base? Also the bases are not the only object that I have in the R data.

You can use the get() function to retrieve an object using a string.

for (i in list.files("Data/Bases/")){
  
  path<-i %>%
    str_remove(., "(?<=.)\\..+") 

tmp <- get(path)  

  assign(paste0("vector_",
                path), 
         tibble(posicion= 1:length(names(tmp)),
                      variable= names(tmp)))
  
}

Hello, thanks for the answer! It helped me! I have a question, is there a way to not use assign?
And somehow create the objects by doing

<- tibble(position= 1:length(names(tmp)),
                      variable= names(tmp))

I can't think of how to do it and name the objects correctly.

I do not know of another way to make the assignment but I am not an expert.

okay do not worry. you helped me a lot

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.