[R] substitute, expression and factors

baptiste auguie baptiste.auguie at googlemail.com
Wed May 19 08:54:35 CEST 2010


Thank you for the explanation, and the fortune-ish quote,

“As the documentation for substitute() says, there is no guarantee
that the result makes sense.”

Best,

baptiste

On 19 May 2010 02:59, Duncan Murdoch <murdoch.duncan at gmail.com> wrote:
> On 18/05/2010 4:36 PM, baptiste auguie wrote:
>>
>> Dear list,
>>
>> I am puzzled by this,
>>
>> substitute(expression(x), list(x = factor(letters[1:2])))
>> # expression(1:2)
>>
>> Why do I get back the factor levels inside the expression and not the
>> labels?
>
> As the documentation for substitute() says, there is no guarantee that the
> result makes sense.  Yours doesn't, and it confuses the deparser, which is
> not displaying what you really have:
>
>> y <- substitute(expression(x), list(x = factor(letters[1:2])))
>> y
> expression(1:2)
>> str(y)
> language expression(structure(1:2, .Label = c("a", "b"), class = "factor"))
>
> The problem is that expressions don't normally have attributes, and factors
> have both .Label and class attributes.  Put another way:  expressions don't
> normally include factors, they include names and calls and atomic vectors.
>  The deparser doesn't distinguish between the language "1:2" and the atomic
> vector that is the value of that expression, but it doesn't expect
> attributes, and doesn't go looking for them.
>
> Duncan Murdoch
>
>> The following work as I expected,
>>
>> substitute(expression(x), list(x = letters[1:2]))
>> # expression(c("a", "b"))
>>
>> substitute(x, list(x = factor(letters[1:2])))
>> # [1] a b
>> # Levels: a b
>>
>>  bquote(.(factor(letters[1:2])))
>> # [1] a b
>> # Levels: a b
>>
>>
>> All the best,
>>
>> baptiste
>>
>> ______________________________________________
>> 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