[R] accessing elements located after $ symbol

Joshua Wiley jwiley.psych at gmail.com
Tue Oct 5 08:24:02 CEST 2010


Dear Lorenzo,

This is the trade off that comes with convenience.  The `$` operator
passes its argument directly as I understand it.  This is what lets
you pass unquoted names that not variables.  The way around it is to
use the `[` extraction operator.  Look at these examples:

test[interest]
#or
test[, interest]
# but
test[first]
test[,first]

Notice that for `[`, the name of the column _must_ be quoted, or be an
object itself.  Typing:

test$interest

is trying to look up the 'interest' column, which does not exist, and
is equivalent to:  test[,"interest"] which is clearly not what you
want.

HTH,

Josh

P.S. I am sure there are others who could provide a more detailed
description.  `$` is primitive and I am only used to R code, so I have
never actually looked through its source.

On Mon, Oct 4, 2010 at 10:45 PM, Lorenzo Cattarino
<l.cattarino at uq.edu.au> wrote:
> Hi R-users
>
>
>
> I am having troubles accessing elements after the $ symbol. Reproducible
> example:
>
>
>
>>test <- data.frame (first=1:10, second=11:20, third=21:30)
>
>>test$first #this works fine
>
>
>
> but when I try
>
>
>
>>interest <- "first"
>
>>test$interest # does not seem to work
>
>
>
> Could you tell me why that happens and show how to do instead?
>
>
>
> Thanks so much
>
> Lorenzo
>
>
>
>
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Joshua Wiley
Ph.D. Student, Health Psychology
University of California, Los Angeles
http://www.joshuawiley.com/



More information about the R-help mailing list