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?
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)
fac:1
$ymin:
[1] 1
$xmin:
[1] 5
-----------------------------------------------------------
fac:2
$ymin:
[1] 2
$xmin:
[1] 19
-----------------------------------------------------------
fac:3
$ymin:
[1] 4
$xmin:
[1] 23
________________________________________________
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
________________________________________________