Inside the plot generated in a chunk in a knitr/LaTeX document I want to position a text string with a reference to a particular figure elsehwere in the document, something like "See Fig. 10", based on the label of a that particular figure, lets say "fig:sim1". So I wrote the following R function which reads the .aux file of the LaTeX-document I'm writing and extracts the counter of the figure matching a specific label
ref <- function(label) {
lines <- scan("mismatch-final.aux","character",sep="\n")
line <- grep(paste("\\{",label,"\\}",sep=""),lines,value=TRUE)
strsplit(strsplit(line,"\\{\\{")[[1]][2],"\\}\\{")[[1]][1]
}
I can then generate the desired text string from within the chunk and place it inside the plot with something like
text(5,10,paste("See Fig.~",ref("fig:sim1")))
This should work but perhaps there is a cleaner way of doing this? Also, is there a way to get at the .aux filename from within the chunk such that the ref function above would be made more general?