Re: [R] Need a more efficient way to implement this type of logic in R

From: Duncan Murdoch <murdoch.duncan_at_gmail.com>
Date: Wed, 06 Apr 2011 16:48:37 -0400

On 06/04/2011 4:02 PM, Walter Anderson wrote:
> I have cobbled together the following logic. It works but is very
> slow. I'm sure that there must be a better r-specific way to implement
> this kind of thing, but have been unable to find/understand one. Any
> help would be appreciated.
>
> hh.sub<- households[c("HOUSEID","HHFAMINC")]
> for (indx in 1:length(hh.sub$HOUSEID)) {
> if ((hh.sub$HHFAMINC[indx] == '01') | (hh.sub$HHFAMINC[indx] == '02')
> | (hh.sub$HHFAMINC[indx] == '03') | (hh.sub$HHFAMINC[indx] == '04') |
> (hh.sub$HHFAMINC[indx] == '05'))
> hh.sub$CS_FAMINC[indx]<- 1 # Less than $25,000

The answer is to think in terms of vectors and logical indexing. The code above is equivalent to

hh.sub$CS_FAMINC[ hh.sub$HHFAMINC %in% c('01', '02', '03', '04', '05') ] <- 1

I've left off the rest of the loop, but I think it's similar.

Duncan Murdoch



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. Received on Wed 06 Apr 2011 - 20:55:53 GMT

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Wed 06 Apr 2011 - 21:00:27 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive