[R] vectorizing data.frame()

Prof Brian Ripley ripley at stats.ox.ac.uk
Mon May 26 09:29:50 CEST 2003


That's a misleading title!

You want a single vector by concatenating vectors and recording their
origins.  There's no need for a data frame, and you are certainly not 
`vectorizing data.frame()'.  I presume you want to do this for a list of 
vectors.  How about

use <- c("foo", "bar")
names(use) <- use
xx <- unlist(lapply(use, get))
names(xx) <- sub("[0-9]+$", "", names(xx))
data.frame(names=names(xx), value=xx)

?

That will work with any character vector of names of vectors not ending in 
a digit.

On Mon, 26 May 2003, Robin Hankin wrote:

> Hello everybody.
> 
> I have a dozen or so vectors (of different lengths) which I want to
> coalesce into a dataframe, as in the following toy example.
> 
> R> foo <- c(1,2,3)
> R> bar <- c(7,8)
> R> data.frame(name =c(rep("foo",length(foo)),rep("bar",length(bar))),
>               value=c(foo,bar))
> 
>   name value
> 1   foo     1
> 2   foo     2
> 3   foo     3
> 4   bar     7
> 5   bar     8
> 
> Is there a better (vectorized) way?
> 
> 
> 

-- 
Brian D. Ripley,                  ripley at 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




More information about the R-help mailing list