how do I access the actual used factor combination in a by() call?
I want to plot results from a dbscan (fpc-package) and add the corresponding factor combination to the plot title. The output is of class “by”.
Using attributes(res.lst) respectively attr(res.lst,"dimnames") gives me only a global list . I cant map that to the individual used subset of data. So how does the by function “know” which combination is actual used for which subset. Where is this information stored?
I tried to make an easy example (skipping dbscan) to make it clear what the desired output should look like. Any help? I want to stick to base R if it’s possible.
dat <- data.frame(x=rnorm(1000), y=rnorm(1000), fac1=rep(c("L1", "L2"), 500), fac2= as.factor(c(rep(1, 5), rep(2, 5) )) ) # dummy data
# dummy plot function
fun.plot <- function(data, factorcomb=NA) {
if (is.na(factorcomb)==T) {
ttl <- "Standard"
} else {
ttl <- paste("factor combination: ", paste(factorcomb, collapse="+"))
}
dev.new()
plot(data$x, data$y, main=ttl)
}
res.lst <- by(data=dat, INDICES=dat[ ,colnames(dat[ , c(3,4)]) ], function(splt) fun.plot(splt) )
# desired result
for (f1 in levels(dat$fac1) ) {
for (f2 in levels(dat$fac2) ) {
fun.plot(dat[ which( dat$fac1==f1 & dat$fac2==f2), 1:2 ], factorcomb=c(f1,f2) )
}
}
EDIT: This is the call from my original function.
# by(data=adat, INDICES=adat[ ,colnames(adat[ ,c(36,41) ]) ], FUN=fun.dbscan, factornames=colnames(adat[ ,c(36,41) ]))
And the output on the coonsole looks like that:
PeakTemp: 250 # Factor 1 (column number 36) + Level
BGANr: BGA196_01 #Factor 2 (column number 41) + Level
dbscan Pts=1551 MinPts=12 eps=0.015
0 1
seed 0 17
border 1534 0
total 1534 17
etc...
I want to pass actual used factor combination to the fun.dbscan function. In that case it would be PeakTemp with level 250 and BGANr BGA196_01
This is similar to what @joran did, but a bit different.
EDIT
If you want to pass custom level names (e.g.
nms), you can try usingmapply. You can fiddle around to formatttlthe way you want it, like replacing dot with a space.