Search code examples
rmatchlattice

Displaying corresponding value of a column by matching it to value of the second column


Generated two datasets as below:

  H<-data.frame(replicate(10,sample(0:20,10,rep=TRUE)))  
  G<-data.frame(replicate(10,sample(0:20,10,rep=TRUE)))  
  H[c(2,3,7,9),9]<-NA
  G[c(1,5,7,8),9]<-NA
  H$diff<-H$X10-H$X9
  G$diff<-G$X10-G$X9
  H$perc<-round((H$diff/H$X10)*100,1)
  G$perc<-round((G$diff/G$X10)*100,1)

Created a plot using:

library(lattice)
xyplot(X8+X9+X10~X1,H,type=c('p','l','g'),
col = c('yellow', 'green', 'blue','red'),
ylab='Count',layout=c(3, 1), 
xlab=paste("H",'difference',min(pmin(H$perc, na.rm = TRUE),na.rm=TRUE),
'% change count'))

I'm trying to get the code to display the value of corresponding difference from the "diff" column and the value from X2 column, along with the lowest difference (which is what the min function is doing). I've tried using "match" in vain. Could someone help please?


Solution

  • May be you can try

    ind <- which.min(H$perc)
    label1 <- paste0("H difference ", H$diff[ind], "% change count")
    label2 <- paste('X2 value', H$X2[ind])
    xyplot(X8+X9+X10~X1,H,type=c('p','l','g'),
    col = c('yellow', 'green', 'blue','red'),
    ylab='Count',layout=c(3, 1), 
    xlab=paste(label1, label2, sep=", "))
    

    Update

    If you have multiple datasets, create a function

    labelfn <- function(dat, Col1, Col2, diffCol){
      args <- as.list(match.call())[-1]
      e1 <- eval(args$Col1, dat)
      e2 <- eval(args$Col2, dat)
      e3 <- eval(args$diffCol, dat)
      ind <- which.min(e1)
      label1 <- paste0(deparse(args[[1]]), ' difference ', 
               e3[ind], '% change count')
      label2 <- paste(deparse(args[[3]]), ' value', e2[ind])
      paste(label1, label2, sep=", ")
     }
    
     labelfn(G, perc, X2, diff)
     #[1] "G difference -14% change count, X2  value 5"
      labelfn(H, perc, X2, diff)
     #[1] "H difference -2% change count, X2  value 18"