Tordir
Tordir

Reputation: 313

Loop over data frames

I am creating a panel from multiple cross sections and I therefore need to label the cross section with the year (before appending the cross sections). More specifically I have data frames of the following form: df2000, df2001, df2002..., and for each such data frame I need to create a variable "Year", that is constant and equal to the current year (i.e., 2001 for 2001 and so on). What is the best way to loop over multiple data frames in order to do this? Even more specifically, how do I create a loop that does the following:

df2000["Year"]<-2000  
df2001["Year"]<-2001  
df2002["Year"]<-2002  
.  
.
.

Upvotes: 0

Views: 52

Answers (1)

boski
boski

Reputation: 2467

As jogo said in the comments, it is way better to work on your dataframes in a list context. Else, you can use get() and assign() as so:

years = c("2000","2001","2002")  # vector containing the years
for (i in years){
    aux = get(paste0("df",i))    # get the variable from the environment (e.g. df2000)
    aux["Year"] = i              # update the "Year" field
    assign(paste0("df",i),aux)  # assign it again to the global environment
}

Upvotes: 1

Related Questions