Best I know, they are effectively the same** within R but I prefer "[" for a
couple of reasons.

1) "[" works for all data types, while $ is sometimes picky: e.g.,

x = matrix(rnorm(9),3); colnames(x) <- c("a","b","c")
x.df = as.data.frame(x)
x$a gives "Error in x$a : $ operator is invalid for atomic vectors"

while

x.df$a works as desired.

2) You can do computations inside of [] that you can't with $: this is a
little contrived, but consider

x.n = names(x.df)
for (i in 1:3)  {
     print(x.df[x.n[i]])
}

works as expected while

x.n = names(x.df)
for (i in 1:3)  {
     print(x.df$(x.n[i]))
}

does not.

3) "[" gives you access to the super-useful "drop" option.

For more info see ? "["

In short, "[" is more flexible and powerful (at least in my experience)
while $ saves the occasional keystroke here and there.

Michael Weylandt

** Caveat that you probably don't need at this point in the learning curve:
the documentation says $ is actually closer to "[[" which can be subtly
different than "[". See ?"[" for the differences.

On Wed, Aug 3, 2011 at 11:43 AM, Justin <jtor14@gmail.com> wrote:

> zcatav <zcatav <at> gmail.com> writes:
>
> >
> > Your suggestion works perfect as i pointed previous message. Now have
> another
> > question about data editing. I try this code:
> > X[X[,"c"]==1,"b"]<-X[,"d"]
> > and results with error: `[<-.data.frame`(`*tmp*`, X[, "c"] == 1, "b",
> value
> > = c(NA,  :
> >   replacement has 9 rows, data has 2
> >
>
> is this equivalent and/or preferred to:
>
> X$b[X$c==1]<-X$d[X$c==1] ??
>
> I assume this goes back to the various indexing methods for a dataframe, an
> object vector that is a column of a data frame vs. an object data frame
> that
> happens to be one column of a larger data frame.
>
> on a very large data set is one preferable for speed?  one for memory use?
>
> I tend to index using $ operators often and if I should quit let me know!!
>
>
> Thanks,
>
> Justin
>
> > Logically i selected 2 rows with X[,"c"]==1. Than i want to replace in
> that
> > rows its own data from "d" to "b" with X[,"b"]<-X[,"d"]. What is wrong?
> >
> > --
> > View this message in context:
>
> http://r.789695.n4.nabble.com/conditional-data-replace-recode-change-or-whatsoever-tp3714715p3715218.html
> > Sent from the R help mailing list archive at Nabble.com.
> >
> >
>
> ______________________________________________
> R-help@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.
>

	[[alternative HTML version deleted]]

