[R] help about R basic

Sarah Goslee sarah.goslee at gmail.com
Sun Sep 25 16:05:40 CEST 2011


On Sun, Sep 25, 2011 at 9:40 AM, David Winsemius <dwinsemius at comcast.net> wrote:

> (I do not know why Sarah Goslee is telling you that you cannot access
> matrices with column names. You clearly can do so. Maybe I misread her
> statement.)

I suppose I should have said that you can't access matrices via column
name *like that*. A data frame is a list, so it can be accessed in the
way in which the original querent was trying. And the latter is by no
means the "wrong way" to do so, merely a way that cannot be used
with matrices. David points out the correct way to access columns of
a matrix by name.

But do note that the default results of x["a"] and x[,"a"] differ, even if x is
a data frame.

> x <- cbind(a=1:3, b=11:13)
> class(x)
[1] "matrix"
> x["a"]
[1] NA
> x[,"a"]
[1] 1 2 3
>
> x <- data.frame(x)
> class(x)
[1] "data.frame"
> x["a"]
  a
1 1
2 2
3 3
> x[,"a"]
[1] 1 2 3
> x[["a"]]
[1] 1 2 3
>
> class(x["a"])
[1] "data.frame"
> class(x[,"a"])
[1] "integer"
> class(x[["a"]])
[1] "integer"
>
> class(x[,"a", drop=FALSE])
[1] "data.frame"
>

There are several entirely valid ways to access named columns, and
they're all slightly different. Which is guaranteed to confuse the
new R user, really.

Sarah

-- 
Sarah Goslee
http://www.functionaldiversity.org



More information about the R-help mailing list