[R] Extract rows from a matrix according to value in column

Ista Zahn izahn at psych.rochester.edu
Wed Aug 3 04:34:30 CEST 2011


Hi Sverre,

On Tue, Aug 2, 2011 at 10:22 PM, Sverre Stausland
<johnsen at fas.harvard.edu> wrote:
> Dear helpers,
>
> I'm trying to extract certain rows from a matrix according to the
> values the rows have in a certain column. I've been googling for a
> while without result.
>
> Here's a reproducible example of a matrix (and the one I was playing
> with initially):
>
>> myrepo<-getOption("repos")
>> myrepo["CRAN"]<-"http://software.rc.fas.harvard.edu/mirrors/R/"
>> class(available.packages(contriburl=contrib.url(myrepo)))
> [1] "matrix"
>
> I can extract according to rows and column positions:
>
>> available.packages(contriburl=contrib.url(myrepo))[2,2]
> [1] "0.1"
>
> But how can I extract the rows according to their values in a column,
> when $ is not usable for vector matrices? Say I would like all the
> rows where the value in the column "Version" is "0.1" (as above). For
> a data frame, I would have done it like this:
>
>> available.packages(contriburl=contrib.url(myrepo))->avail.pack
>> avail.pack[avail.pack$Version=="0.1",]
> Error in avail.pack$Version : $ operator is invalid for atomic vectors

Use [ instead of $, like this:

avail.pack[avail.pack[, "Version"] == "0.1", ]

best,
Ista

>
> Also, thanks to those who responded to my recent question in
> https://stat.ethz.ch/pipermail/r-help/2011-August/285650.html (I
> assume it's best not to respond at the end of threads with a "thank
> you" only, to avoid cluttering people's inboxes?)
>
> best
> Sverre
>
> ______________________________________________
> 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.
>



-- 
Ista Zahn
Graduate student
University of Rochester
Department of Clinical and Social Psychology
http://yourpsyche.org



More information about the R-help mailing list