[R] changing character to a vector name
Gabor Grothendieck
ggrothendieck at myway.com
Tue Nov 16 21:35:44 CET 2004
Laura Holt <lauraholt_983 <at> hotmail.com> writes:
.> I would like to generate a vector/variable name from within a loop to be
.> passed to a table
.> function.
.>
.> This is what I have so far:
.> >assign("p1",paste("raw3.df$",rw2$V1[3],sep=""))
.> >p1
.> [1] "raw3.df$CITIZEN"
.> >
.> Essentially, I want to use the raw3.df$CITIZEN along with another value to
.> generate a table.
You can use eval and parse to parse and execute
arbitrary R commands that you construct from strings. The exec
function below is a one statement convenience function
that pastes its arguments together and executes them this way in
its parent's environment. (Sometimes when one gets complex
requirements like this if one backs up a bit one discovers
that the requirements can be simplified and you might
consider whether that is the case here in which case you
might be able to disregard all this.)
R> ### create some test data ###
R> data(iris)
R> irish <- head(iris)
R> irish
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa
R> ### this is the actual processing ###
R> exec <- function(...) eval.parent(parse(text = paste(..., collapse = "")))
R> exec("irish$Sepal.Length", "<-", "irish$Sepal.Length", "+1")
R> irish
Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 6.1 3.5 1.4 0.2 setosa
2 5.9 3.0 1.4 0.2 setosa
3 5.7 3.2 1.3 0.2 setosa
4 5.6 3.1 1.5 0.2 setosa
5 6.0 3.6 1.4 0.2 setosa
6 6.4 3.9 1.7 0.4 setosa
More information about the R-help
mailing list