Re: [R] Query about extracting subset of datafram

From: Marc Schwartz <marc_schwartz_at_comcast.net>
Date: Wed 24 Jan 2007 - 21:10:51 GMT

On Wed, 2007-01-24 at 12:31 -0800, lalitha viswanath wrote:
> Hi
> I have a table read from a mysql database which is of
> the kind
>
> clusterid clockrate
>
> I obtained this table in R as
> clockrates_table <-sqlQuery(channel,"select....");
> I have a function within which I wish to extract the
> clusterid for a given cluster.
> Although I know that there is just one row per
> clusterid in the data frame, I am using subset to
> extract the clockrate.
>
> clockrate = subset(clockrates_table, clusterid==15,
> select=c(clockrate));

You don't need the ';', though some will argue that it is a personal preference. Also, the c(...) around 'clockrate' is not needed when only one column is being selected.

> Is there any way of extracting the clockrate without
> using subset.

You could use:

  clockrates_table[clockrates_table$clusterid == 15,

                   clockrates_table$clockrate]

or perhaps:

  with(clockrates_table, clockrates_table[clusterid == 15, clockrate])

See ?with

If you did not need the conditional, you could of course use:

  clockrates_table$clockrate

or:

  clockrates_table[["clockrate"]]

or:

  clockrates_table[, "clockrate"]

or:

  with(clockrates_table, clockrate)

My personal preference is to use subset(), as for me, it makes the code easier to read.

> In the help section for subset, it mentioned to "see
> also: [,..."
> However I could find no mention for this entry when I
> searched as "?[", etc.

Try: ?"[" or ?Extract

Note the placement of the quotes in the first case.

> The R manuals also, despite discussing complex
> libraries, techniques etc, dont always seem to provide
> such handy hints/tips and tricks for manipulating
> data, which is a first stumbling block for newbies
> like me.
> I would greatly appreciate if you could point me to
> such resources as well, for future reference.

If you have not yet, reading the Posting Guide, for which there is a link at the bottom of each e-mail is a good place to start.

Also, see ?RSiteSearch for a function which will enable you to search the e-mail list archives.

HTH, Marc Schwartz



R-help@stat.math.ethz.ch 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. Received on Thu Jan 25 14:12:21 2007

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.1.8, at Thu 25 Jan 2007 - 03:30:31 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.