简体   繁体   中英

Loop over several dataframes in R

I have several data frames that I would like to be used in the same code, one after the other. In the code lines that I have written, I am using the variable "my_data" (which is basically a dataframe). Thus, I thought the easiest solution would be to assign each of my other dataframes to "my_data", one after the other, so that all the code that follows can be executed for each data frame in a loop without changing the code I already have.

The structure I have looks as follows:

#Datasets:
    my_data
    
    age_date
    gender_data
    income_data

   ## Code that uses "my_data" follows here" ##

How can I create a loop that first assigns "age_data" to "my_data" and executes the code where "my_data" was used as a variable. Then, after it reaches the end, restarts and assigns "gender_data" to the variable "my_data" and does the same until this has been done for all variables.

Help is much appreciated!

I am attempting to answer based upon information provided:

datanames <- c("age_data","gender_data","income_data")

for (dname in datanames){
 my_data <- data.frame()
 my_data <- get(dname)
 # here you can write rest of the code
 rm(mydata)
}

Maybe you can try get within for loop

for (i in c(  "age_date", "gender_data","income_data")) {
  my_data <- get(i)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM