[R] convert expressions to characters

Duncan Murdoch murdoch.duncan at gmail.com
Wed Jan 5 23:10:11 CET 2011


On 11-01-05 4:47 PM, Yihui Xie wrote:
 > Hi,
 >
 > Suppose I have
 >
 > x = parse(text = "
 > {y=50+50+50#'asfasf'
 > }
 > ")
 >
 > now x is an expression with some src attributes.
 >
 >> x
 > expression({y=50+50+50#'asfasf'
 > })
 > attr(,"srcfile")
 > <text>
 > attr(,"wholeSrcref")
 >
 > {y=50+50+50#'asfasf'
 > }
 >
 > My question is, how can I get my string back (the string passed to
 > parse() as the text argument)?

You can use

as.character(attr(x, "wholeSrcref"))

If length(x) > 1, you can get the parts corresponding to each expression 
within it as

for (i in 1:length(x)) {

print (as.character(attr(x, "srcref")[[i]]))

}

but this leaves off comments and whitespace that are not embedded within 
the expressions the way your comment is.

Duncan Murdoch



 >
 >> as.character(x)
 > [1] "{"
 >
 > as.character() only returns "{".
 >
 >> as.character(expression({1}))
 > [1] "{"
 >> as.character(expression("1","2+3"))
 > [1] "1"   "2+3"
 >
 >
 > Thanks a lot!
 >
 > Regards,
 > Yihui
 > --
 > Yihui Xie<xieyihui at gmail.com>
 > Phone: 515-294-2465 Web: http://yihui.name
 > Department of Statistics, Iowa State University
 > 2215 Snedecor Hall, Ames, IA
 >
 > ______________________________________________
 > 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