An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20111009/f56c8f94/attachment.pl>
variable name question
4 messages · Deepankar Basu, R. Michael Weylandt, Rolf Turner
"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.
On 10/10/11 04:53, R. Michael Weylandt wrote:
<SNIP>
Try this:
for (i in 1990:2009) {
varName = paste("pci", i, collapse = "")
assign(varName, log(get(varName))
}
<SNIP>
I believe that ``sep= " '' is needed here rather than collapse.
Try:
paste("junk",42,collapse="")
You get
[1] "junk 42"
with a space in it. Here paste is using the default value of sep,
namely " ",
and is not using collapse at all, since there is nothing to collapse (the
value is a scalar to start with).
Whereas
paste("junk",42,sep="")
gives
[1] "junk42"
which is what is wanted.
cheers,
Rolf Turner
An embedded and charset-unspecified text was scrubbed... Name: not available URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20111009/82596283/attachment.pl>