s-news
[Top] [All Lists]

Re: accessing a column of a matrix using strings

To: Spencer Graves <spencer.graves@pdf.com>
Subject: Re: accessing a column of a matrix using strings
From: Prof Brian Ripley <ripley@stats.ox.ac.uk>
Date: Mon, 28 Jul 2003 08:09:15 +0100 (BST)
Cc: "Leeds, Mark" <mleeds@mlp.com>, <s-news@wubios.wustl.edu>
In-reply-to: <3F246A9F.2040608@pdf.com>
On Sun, 27 Jul 2003, Spencer Graves wrote:

> I get the following from S-Plus 6.1 under Windows 2000:
>  > (d2x2 <- matrix(1:4, 2, dimnames = list(c("9", "8"), c("3", "4"))))
>    3 4
> 9 1 3
> 8 2 4
>  > d2x2[, "3"]
>   9 8
>   1 2
>  > d2x2["9",  , drop = F]
>    3 4
> 9 1 3
> 
> hope this helps.  spencer graves

That implies that "8344" is the name of a column.  If it is part of the 
contents of a column (which is what Mark actually said) it would need to 
be

mode(d2x2) <- "character"
ticker1 <- "3"
inds <- unlist(apply(d2x2, 2, function(x) length(grep(ticker1, x))> 0))
d2x2[, inds]
  9   8 
"3" "4" 

inds is a logic variable indicating if the string value of ticker1 is in 
the column.

> 
> Leeds, Mark wrote:
> > I think this question is pretty basic but i have been stuck for a while.
> >  
> > i have a matrix whose columns are strings such as "8344", "8312" etc.

columns or column names?

> > later on, in a program, i have a variable called ticker1 which is a string
> > such as the above. so , i want to access the column corresponding
> > to whatever string ticker1 is.
> >  
> > i tried matrix[,ticker1]  : this gives me back weird stuff which i kind
> > of expected.
> >  
> > i tried matrix[,get(ticker1)] : this gives me back "object "8344" not found.


-- 
Brian D. Ripley,                  ripley@stats.ox.ac.uk
Professor of Applied Statistics,  http://www.stats.ox.ac.uk/~ripley/
University of Oxford,             Tel:  +44 1865 272861 (self)
1 South Parks Road,                     +44 1865 272866 (PA)
Oxford OX1 3TG, UK                Fax:  +44 1865 272595


<Prev in Thread] Current Thread [Next in Thread>