The Parsing = operator in R does not produce a language object

I am trying to manipulate some parsed R-code and ran into difficulties with the = operator. As this fragment shows, I can get an object that says its type is β€œlanguage”, but then returns false in the β€œis” test, which R uses when assigning a value to the slot of class S4.

Here is a sample code:

parsed <- parse(text = "cylinders = c(4, 6, 8)") print (typeof(parsed)) # Prints "expression" langObj <- parsed[[1]] print (typeof(langObj)) # Prints "language" print (is(langObj, "language")) # Prints FALSE setClass("Foo", slots = list( s1 = "language") ) setMethod ("initialize", "Foo", function(.Object, obj){ .Object@s1 <- obj return (.Object) } ) new (Class = "Foo", langObj) 

This last line causes an error:

 Error in (function (cl, name, valueClass) : assignment of an object of class "=" is not valid for @'s1' in an object of class "Foo"; is(value, "language") is not TRUE 

Note that if the <- operator is used instead of =, the code works as expected.

What is the difference between "typeof" and "is"? Why the operator "=" does not give the value "language", and <- does?

+6
source share
1 answer

You need to understand that typeof returns a rather low level characteristic and that is( ... , "language") checks for a slightly higher level of abstraction. typeof little use. It is usually more useful to query the class of an object:

 > class(parsed) [1] "expression" > class(parsed[[1]]) [1] "=" 

This second one may seem a little strange, and I would think that it is the result of eitehr a call or or Ops , but if you look at:

 parsed[[1]] #cylinders = c(4, 6, 8) 

You see that the call object represents internally, that is, a parsing tree, like:

 `=`( cylinders, c(4, 6, 8) ) 

... noting that:

  parsed[[1]][[1]] `=` # note the backticks signifying a function, a language object 

... and that this is really an object call:

  is.call( parsed[[1]] ) #[1] TRUE 

See ?parse Parse for a description of the function returning an invaluable call object. I'm more of an S3 guy, so I'm trying to explain what happens to your S4 stuff above my pay level. Please note that the error message from your unsuccessful S4 attempts referred to a "class" mismatch, not a "typeof"

+2
source

All Articles