0

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  
.  
.
.
1
  • 1
    It is better to have the dataframes df2000, df2001, df2002... in a list. Commented Jun 12, 2019 at 10:09

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.