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

Marc Schwartz marc_schwartz at me.com
Thu Jun 4 05:02:24 CEST 2009


On Jun 3, 2009, at 9:45 PM, Jason Rupert wrote:

>
> 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)
>
> 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"



Yep, definitely an easier way:

HouseDates <- c("02/27/90", "02/27/91", "01/14/92", "02/28/93",  
"02/01/94", "02/01/95", "02/01/96")

# You can convert the entire *vector* to a Date and then format the  
result to Year only.
# See ?format.Date

 > format(as.Date(HouseDates, "%m/%d/%y"), "%Y")
[1] "1990" "1991" "1992" "1993" "1994" "1995" "1996"


One of the key things to bear in mind about R, is that in general  
(there are exceptions), avoiding explicit 'for' loops is a paradigm. R  
is by design, a vectorized language. That means that many operations  
are designed to take a vector, matrix or array and operate on it in a  
"whole object" fashion. Essentially, iterate an operation over the  
entire object with a single function call.

If you are coming from a different programming language, this is  
perhaps one of the more challenging perspectives to achieve. But once  
you make that leap, you will look back and be amazed at how you ever  
managed to get things before (and how many lines of code it took...)

If you have not, read through 'An Introduction to R', provided with  
your R distribution or on the R web site. It's a good place to start  
and there are other contributed materials and books listed on the R  
web site that can supplement that as you progress.

HTH,

Marc Schwartz




More information about the R-help mailing list