[R] Evaluating an expression

Janszen, Derek derek.janszen at precisionformedicine.com
Mon Apr 4 18:22:53 CEST 2016


Hi,

I want to create a data frame similar to the following, but greatly scaled up:
df <- data.frame(aaa= c("a","b","c"), integer(3), integer(3))
names(df)[2:3] <- paste("var",1:2,sep="")
which yields
  aaa  var1  var2
1   a     0     0
2   b     0     0
3   c     0     0

I would not relish having to paste 'integer(3)' 5000 times :(

So (I figure) there must be a way to do this programmatically, something akin to
exp1 <- paste(rep("integer(3)",2),collapse=',')
which looks like it might work:     "integer(3),integer(3)" , as in the following
df <- data.frame(aaa=xxx, eval(parse(text=exp1)))
but this yields

Error in parse(text = exp1) : <text>:1:11: unexpected ','

1: integer(3),

              ^


Not sure just why this doesn't work (?parse does not help), but it's not important right now.

I have used eval and parse in the past, but not in a way similar to what I'm trying to do now.



exp1 <- rep("integer(3)",2) gives "integer(3)" "integer(3)"

and upon parse(text=exp1) gives expression(integer(3), integer(3))

which appears to be promising, and does not give an error in the following

        df <- data.frame(aaa=xxx, eval(parse(text=exp1)))

but alas, does not give the desired result
  aaa eval.parse.text...exp1..
1   a                        0
2   b                        0
3   c                        0




I'm guessing that only the last evaluation of the expression is being evaluated, which I can understand.

I feel certain that what I want to accomplish can be done programmatically, but am at a loss as to just how to do that.
Chances are this has been covered before. If so, apologies.
If not, can anyone point me to references with more info than the help pages, or suggest a solution? :)

Thanks,
Derek

Derek Janszen, PhD
Statistician, Analytics

Precision for Medicine<http://www.precisionformedicine.com/>
8425 Progress Drive, Suite M | Frederick, MD 21701
+1 240 415 6004 office



The information contained in this email and any attachments is confidential and may be subject to copyright or other intellectual property protection. If you are not the intended recipient, you are not authorized to use or disclose this information, and we request that you notify us by reply mail or telephone and delete the original message from your mail system.

	[[alternative HTML version deleted]]



More information about the R-help mailing list