[R] variable name question

R. Michael Weylandt michael.weylandt at gmail.com
Sun Oct 9 17:53:26 CEST 2011


"This is surely an easy question but somehow I am not being able to get it."

get() is the key -- it takes a string and returns the object with that
string as its name. Assign() goes the other way

Try this:

for (i in 1990:2009) {
    varName = paste("pci", i, collapse = "")
    assign(varName, log(get(varName))
}

That said, the standard advice is that its usually more R-ish to keep
all your data in a list, data frame or, for this case, a matrix.

Michael

On Sun, Oct 9, 2011 at 11:46 AM, Deepankar Basu <basu.15 at gmail.com> wrote:
> Hi All,
>
> This is surely an easy question but somehow I am not being able to get it.
>
> I am using R 2.13.2 and have a data set where variable names like this
> appear:
>
> pci1990, pci1991, ... , pci2009.
>
> "pci1990" has data on per capita income for 1990, "pci1991" has data on per
> capita income for 1991, and so on.
>
> I would like to create the logarithm of per capita for each of the year and
> could do so in STATA with the following commands:
>
> forvalues number = 1990/2009 {
>    gen lpci`number' = log(pci`number')
> }
>
> What would be the corresponding set of commands in R?
>
> Thanks a lot in advance.
>
> Deepankar
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list