[R] Getting a column of values from a list - think I'm doing it the hard way

Gavin Simpson gavin.simpson at ucl.ac.uk
Thu Jun 4 09:10:24 CEST 2009


On Thu, 2009-06-04 at 10:57 +0800, Ronggui Huang wrote:
> 2009/6/4 Jason Rupert <jasonkrupert at yahoo.com>:
<snip />
> > HouseDates <- c("02/27/90", "02/27/91", "01/14/92", "02/28/93", "02/01/94", "02/01/95", "02/01/96")
> >
> > # ?as.Date
> > HouseDatesFormatted<-as.Date(HouseDates, "%m/%d/%y")
> >
> > HouseDatesFormatted
> >
> > HouseDatesList<-strsplit(as.character(HouseDatesFormatted), "-", fixed=TRUE)
> 
> > sapply(HouseDatesList,function(x) x[[1]])
> [1] "1990" "1991" "1992" "1993" "1994" "1995" "1996"

Marc has provided a more direct way of achieving the result that the OP
wanted, but as I often find myself writing sapply calls like Ronggui's,
it is worth pointing out you can simplify such calls by dropping the
anonymous function. In this case we can apply the `[[` function. '1' is
an argument to this function, which sapply() allows us to pass on the
sapply-ed function:

> sapply(HouseDatesList, `[[`, 1)
[1] "1990" "1991" "1992" "1993" "1994" "1995" "1996"

For some reason, this idiom has been slow to catch on in my brain...

G

> 
> 
> > HouseYear_array<-NULL
> > length_array<-length(HouseDatesList)
> > for(ii in 1:length_array)
> > {
> >        HouseYear<-HouseDatesList[[ii]][1]
> >
> >        HouseYear_array<-c(HouseYear_array, HouseYear)
> > }
> >
> > as.character(HouseYear_array)
> >
> > # Desired:
> > # [1] "1990" "1991" "1992" "1993" "1994" "1995" "1996"
> >
> > ______________________________________________
> > 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.
> >
> 
> 
> 
-- 
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%
 Dr. Gavin Simpson             [t] +44 (0)20 7679 0522
 ECRC, UCL Geography,          [f] +44 (0)20 7679 0565
 Pearson Building,             [e] gavin.simpsonATNOSPAMucl.ac.uk
 Gower Street, London          [w] http://www.ucl.ac.uk/~ucfagls/
 UK. WC1E 6BT.                 [w] http://www.freshwaters.org.uk
%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%~%




More information about the R-help mailing list