[R] Selecting a subgroup

Jim Lemon bitwrit at ozemail.com.au
Mon Jan 18 11:50:22 CET 1999


		

I use the following function to select a subgroup from a data vector
(usually to calculate descriptive stats).

select.range<-function (groupvec, min, max, data)
{
    if (nargs() > 3) {
        min.cond <- groupvec >= min
        max.cond <- groupvec < max
        cond <- min.cond & max.cond
        selected <- na.remove(ifelse(cond, data, NA))
        invisible(selected)
    }
    else cat("Usage: select.range(groupvec,min,max,datavec)\n")
}

e.g.

> tdata.df<-read.table("tdata",header=T,sep=",")
> tdata.df
   group value year
1      1     0 1980
2      1    10 1981
3      1    14 1982
4      1    20 1983
5      1    25 1984
6      1    30 1985
7      2     0 1980
8      2     5 1981
9      2     6 1982
10     2     8 1984
11     3     0 1984
12     3     2 1985
13     4     0 1980
14     4    20 1981
15     4    30 1982
16     4    30 1984
17     4    35 1985
> value1<-select.range(tdata.df$group,1,1.1,tdata.df$value)
> value1
[1]  0 10 14 20 25 30

Note that you cannot use 1,1 as the range - you'll get an empty result.

Apologies if it's not sufficiently elegant.

Jim

-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-
r-help mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-help-request at stat.math.ethz.ch
_._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._._



More information about the R-help mailing list