[R] two questions for R beginners
Gustaf Rydevik
gustaf.rydevik at gmail.com
Mon Mar 1 16:18:53 CET 2010
On Mon, Mar 1, 2010 at 4:02 PM, Karl Ove Hufthammer <karl at huftis.org> wrote:
> 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
>
As a technical excercise, I wrote the following function:
'%W%'<-function(e1,e2)e1[,which(colnames(e1)%in%e2)]
temp<-matrix(1:6,nrow=2,dimnames=list(a=1:2,b=c("a","b","c")))
temp%W%"b"
I assume that the reason you can't use $.matrix , is that $ is a
primitive function and doesn't use the UseMethod function.
/Gustaf
--
Gustaf Rydevik, M.Sci.
tel: +46(0)703 051 451
address:Essingetorget 40,112 66 Stockholm, SE
skype:gustaf_rydevik
More information about the R-help
mailing list