How to rewrite this Stata code in R?

后端 未结 4 653
挽巷
挽巷 2021-01-02 07:34

One of the things Stata does well is the way it constructs new variables (see example below). How to do this in R?

foreach i in A B C D {  
    forval n=1990         


        
4条回答
  •  臣服心动
    2021-01-02 08:34

    Assuming popA1989, popB1989, popC1989, popD1989 already exist in your global environment, the code below should work. There are certainly more "R-like" ways to do this, but I wanted to give you something similar to your Stata code.

    for(L in LETTERS[1:4]) {
      for(i in 1990:2000) {
        new <- paste("pop",L,i,sep="")  # create name for new variable
        old <- get(paste("pop",L,i-1,sep=""))  # get old variable
        trend <- get(paste("trend",i,sep=""))  # get trend variable
        assign(new, old*(1+trend))
      }
    }
    

提交回复
热议问题