简体   繁体   English

在 R 中循环多个数据帧

[英]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).在我编写的代码行中,我使用了变量“my_data”(基本上是一个数据框)。 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.因此,我认为最简单的解决方案是将我的每个其他数据帧一个接一个地分配给“my_data”,以便可以在循环中为每个数据帧执行以下所有代码,而无需更改我已经拥有的代码.

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.如何创建一个循环,首先将“age_data”分配给“my_data”并执行将“my_data”用作变量的代码。 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.然后,在它到达末尾后,重新启动并将“gender_data”分配给变量“my_data”并执行相同的操作,直到对所有变量都完成此操作。

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也许你可以尝试get for循环

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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