[R] two questions for R beginners
Karl Ove Hufthammer
karl at huftis.org
Mon Mar 1 16:02:13 CET 2010
On Mon, 01 Mar 2010 09:09:11 -0500 Duncan Murdoch <murdoch at stats.uwo.ca>
wrote:
> >> The reason for the difference is that data.frames are lists organized
> >> into columns (so the $ handling comes from the list, where it means
> >> "extract the component") whereas a matrix is a single vector displayed
> >> in columns.
> >
> > Sure, I know that. But is there are reason why the '$' can't be
> > overloaded to handle the extraction, as a *convenience* to the user?
>
> See the second paragraph of my response.
OK. So I take it that there are no *technical* reasons can't be made to
work for matrices and named vectors? I tried redefining it for matrices
with
`$.matrix`=function(x, name) ... something ...
but I still get an error message when trying to use it.
Of course I agree that 'the idea of a list is so fundamental to R that
it needs to be something learned pretty early', but is there any harm in
slightly 'blur[ing] the distinction between dataframes and matrices', as
a convenience to the user? Or, in other words, what does one *gain* by
having '$' on named matrices and vectors give a confusing error message
instead of the expected results? Dinstinction for dinstinction's own
sake is of little use.
In case anyone is wondering about the vector case (of which matrices is
of course only a special case), here is an example:
> d=iris[,1:4]
> d1=head(d,1)
> d2=mean(d)
>
> d1
Sepal.Length Sepal.Width Petal.Length Petal.Width
1 5.1 3.5 1.4 0.2
> d2
Sepal.Length Sepal.Width Petal.Length Petal.Width
5.843333 3.057333 3.758000 1.199333
>
> d3$Sepal.Width
[1] 3.5
> d4$Sepal.Width
Error in d4$Sepal.Width : $ operator is invalid for atomic vectors
--
Karl Ove Hufthammer
More information about the R-help
mailing list