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

Greg Snow Greg.Snow at imail.org
Thu Jun 4 18:10:15 CEST 2009


If you want to play R golf then:

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

Does the same thing in fewer keystrokes, but Ronggui's solution is more readable.

-- 
Gregory (Greg) L. Snow Ph.D.
Statistical Data Center
Intermountain Healthcare
greg.snow at imail.org
801.408.8111


> -----Original Message-----
> From: r-help-bounces at r-project.org [mailto:r-help-bounces at r-
> project.org] On Behalf Of Ronggui Huang
> Sent: Wednesday, June 03, 2009 8:57 PM
> To: Jason Rupert
> Cc: R-help at r-project.org
> Subject: Re: [R] Getting a column of values from a list - think I'm
> doing it the hard way
> 
> 2009/6/4 Jason Rupert <jasonkrupert at yahoo.com>:
> >
> > Example code it shown below.
> >
> > I think I am doing this the hard way.  I'm just trying to get the
> full year value from an array of dates.  An example array is shown
> below.  Right now, I'm using a "for" loop to pull the year out of a
> list where the dates were split up into their individual components.
> >
> > This seems to work, but just wondering if there is an easier way.
> >
> > Thanks for any insights.
> >
> > #*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
> > 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"
> 
> 
> > 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.
> >
> 
> 
> 
> --
> HUANG Ronggui, Wincent
> PhD Candidate
> Dept of Public and Social Administration
> City University of Hong Kong
> Home page: http://asrr.r-forge.r-project.org/rghuang.html
> 
> ______________________________________________
> 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.




More information about the R-help mailing list