Baghurst, Peter (CYWHS) wrote:
> Hi all,
>
> I am having difficulty coding a simple task of extracting the minimum
> value of a vector y, and the corresponding value of parallel vector x,
> within individual levels level of a factor.
>
> Extracting a minimum value of a single vector, within levels of a
> factor, is just a simple application of “tapply” – but my code for
> extracting the corresponding value from a parallel vector then gets very
> “kludgey”. I can get tantalising close to a clean solution using the
> “by” function, - which produces the output I need (see below), - but I
> just can’t extract those component values for further use in the script.
>
> Any suggestions on how to extract parallel vectors of the minimum and
> the corresponding value of the parallel vector, anyone? Perhaps there is
> some other function that would do this cleanly?
How about this?
y <- c(3, 1, 8, 9, 7, 2, 4, 5, 6)
x <- c(1, 5, 7, 11, 15, 19, 23, 31, 40)
fac <- as.factor(rep(1:3, each = 3))
dta <- data.frame(x = x, y = y, fac = fac)
t(sapply(split(dta, fac), function(df){df[which(df$y ==
min(df$y)),c("x","y")]}))
[,1] [,2]
1 5 1
2 19 2
3 23 4
> Peter Baghurst
>
> y <- c(3, 1, 8, 9, 7, 2, 4, 5, 6)
> x <- c(1, 5, 7, 11, 15, 19, 23, 31, 40)
> fac <- as.factor(rep(1:3, each = 3))
> #
> my.func <- function(dta)
> {
> y <- dta$y
> x <- dta$x
> ymin <- min(y)
> xvalmin <- x[y == ymin]
> return(list(ymin = ymin, xmin = xvalmin))
> }
>
> #
>
> dta <- data.frame(x = x, y = y)
> minpoints <- by(dta, fac, my.func)
> print(minpoints)
> ...
> ________________________________________________
>
> Assoc/Prof Peter A Baghurst,
>
> Head, Public Health Research Unit
>
> Women's and Children's Hospital
>
> Children Youth and Women's Health Service
>
> 72 King William Road
>
> North Adelaide
>
> South Australia 5006
>
> Phone: +61-8-8161 6935
>
> Fax: +61-8-8161 7782
>
> ________________________________________________
--
Chuck Cleland, Ph.D.
NDRI, Inc.
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 512-0171 (M, W, F)
fax: (917) 438-0894
|