From murdoch at stats.uwo.ca  Fri Jul 13 12:52:26 2007
From: murdoch at stats.uwo.ca (Duncan Murdoch)
Date: Fri, 13 Jul 2007 06:52:26 -0400
Subject: [Rd] parse(text=...) and the srcfile attribute
In-Reply-To: <eb555e660707121910i216ea27cvd71a1bf32b36f288@mail.gmail.com>
References: <eb555e660707121852x13817360t5def7f645632e86@mail.gmail.com>	<971536df0707121902t44b214e5r212da62fba7688a@mail.gmail.com>
	<eb555e660707121910i216ea27cvd71a1bf32b36f288@mail.gmail.com>
Message-ID: <4697596A.5030205@stats.uwo.ca>

On 12/07/2007 10:10 PM, Deepayan Sarkar wrote:
> On 7/12/07, Gabor Grothendieck <ggrothendieck at gmail.com> wrote:
>> You can do this:
>>
>>> foo at srcfile$lines
>> [1] "\na <- 1; b <- 2**2\na + b\n"
>>
>>> # or this
>>> as.character(foo)
>> [1] "a <- 1"   "b <- 2^2" "a + b"
> 
> Neither of which is what I want. I want
> 
>> sapply(attr(foo, "srcref"), as.character)
> [1] "a <- 1"    "b <- 2**2" "a + b"
> 
> but was hoping for a better way than this.

I don't think there is one.  The code for print(foo) is deep within the 
deparser, and it never generates the things you want individually, 
they're just part of what gets generated when it deparses foo. (One 
reason for this design is that foo has a srcref attribute, its elements 
don't, because the elements of an expression are not necessarily things 
that can sensibly have attributes.)

So your one-liner is probably the best way to get what you want.

Duncan Murdoch


> -Deepayan
> 
>> On 7/12/07, Deepayan Sarkar <deepayan.sarkar at gmail.com> wrote:
>>> Hi,
>>>
>>> I'm trying to understand whether the new source file references can
>>> help me with something I want to do. Let's say I have
>>>
>>> foo <- parse(text = "
>>> a <- 1; b <- 2**2
>>> a + b
>>> ")
>>>
>>> I now wish to recover the sources for the parsed expressions. I can
>>> get them one at a time:
>>>
>>>> foo[[2]]
>>> b <- 2^2
>>>> as.character(attr(foo, "srcref")[[2]])
>>> [1] "b <- 2**2"
>>>
>>> Is there a better way? Perhaps like the print method
>>>
>>>> as.character(foo, useSource = TRUE)
>>> could give all the sources at once?
>>>
>>> -Deepayan
>>>
>>> ______________________________________________
>>> R-devel at r-project.org mailing list
>>> https://stat.ethz.ch/mailman/listinfo/r-devel
>>>
> 
> ______________________________________________
> R-devel at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-devel



[Rd] parse(text=...) and the srcfile attribute
Duncan Murdoch