[Rd] "with" doesn't work with names with blanks

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Mon May 2 01:01:43 CEST 2022


On 01/05/2022 5:19 p.m., Spencer Graves wrote:
> 
> 
> On 5/1/22 2:51 PM, Duncan Murdoch wrote:
>> On 01/05/2022 3:41 p.m., Spencer Graves wrote:
>>> Hello, All:
>>>
>>>
>>>        Column names in a data.frame are not supposed to have trailing
>>> blanks.  However, a CRAN package created one, which threw an error with
>>> "with".  Consider the following example:
>>>
>>>
>>>    > (tst <- data.frame(1))
>>>      X1
>>> 1  1
>>>    > names(tst) <- 'x '
>>>    > tst$x
>>> [1] 1
>>>    > with(tst, x)
>>> Error in eval(substitute(expr), data, enclos = parent.frame()) :
>     object 'x' not found>>
>>>
>>>        I think it's interesting that "tst$x" works, but "with(txt, x)".
>>>
>>>
>>>        Comments?
>>
>> tst$x works because of partial name matching.  (That leniency is one of
>> the reasons for advice to avoid using $ in programs.)  It would be chaos
>> if with() used partial name matching.
>>
>> You can use
>>
>> with(txt, `x `)
>>
>> to include the space in the name.
> 
> 
> but to use that, I have to KNOW that the name is `x `, not `x`.  It took
> me a while to identify that as the source of the problem:  What I saw
> was that "with(tst

Printing names(tst) would make it somewhat clear.  Running str(tst) 
(which is what I'd do) would hide it:

 > tst$y <- 2
 > tst$x <- 3
 > str(tst)
'data.frame':	1 obs. of  3 variables:
  $ x : num 1
  $ y : num 2
  $ x : num 3

Duncan Murdoch

> 
> 
> 	  And thanks for the reminder that you recommend avoiding use of "$".
> 
> 
> 	  sg
> 
> 
> p.s.  After I found the problem, I fixed it using
> names(x) <- tis::stripBlanks(names(x))
> 
>>
>> Duncan Murdoch
>>
>>>
>>>
>>>        It's not a major problem, though it took me a while to
>>> diagnose.  (I
>>> reported it to the maintainer of the package that returned a data.frame
>>> with names with trailing blanks.)
>>>
>>>
>>>        Thanks, for all your work in maintaining and upgrading R -- and in
>>> responding to emails from this list.
>>>
>>>
>>>        Spencer Graves
>>>
>>>
>>>    > sessionInfo()
>>> R version 4.2.0 (2022-04-22)
>>> Platform: x86_64-apple-darwin17.0 (64-bit)
>>> Running under: macOS Big Sur 11.6.5
>>>
>>> Matrix products: default
>>> LAPACK:
>>> /Library/Frameworks/R.framework/Versions/4.2/Resources/lib/libRlapack.dylib
>>>
>>>
>>> locale:
>>> [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
>>>
>>> attached base packages:
>>> [1] stats     graphics  grDevices utils     datasets  methods   base
>>>
>>> loaded via a namespace (and not attached):
>>> [1] compiler_4.2.0 tools_4.2.0
>>>    >
>>>
>>> ______________________________________________
>>> R-devel using r-project.org mailing list
>>> https://stat.ethz.ch/mailman/listinfo/r-devel
>>



More information about the R-devel mailing list