Feb 16, 2011

Stata or R - How to create dynamic variables in R?

As we dig deeper into Stata or R debate, a few questions have come up.

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

We can rewrite it as-is using for loops in R, which is slow and not elegant. What's the elegant way to write this in R? I haven't used plyr yet... Time to learn it?

Link to question on StackOverflow


  1. Assuming popA1989, popB1989 ... already exist in data.frame dat.

    pop <- LETTERS[1:4]
    years <- 1990:2000

    for(i in years){
    dat[str_c(str_c("pop",pop),i)] <- dat[str_c(str_c("pop",pop),i-1)]*(1+dat[rep(str_c("trend",i-1),length(pop))])

  2. Thank you for your attention in informing well to known facts. Nice review! Also turn your attention that it needs to search for mobile software development companies if you need .

  3. Nice code. Thanks for sharing